이 방법으로 pkg
패키지를 만들었습니다. 아래__all__이 정의되지 않은 경우에도 pkg import *에서 모듈 가져 오기가 끝나는 이유는 무엇입니까?
$ tree
.
└── pkg
├── foo.py
└── __init__.py
1 directory, 2 files
[email protected]:~/so$ cat pkg/__init__.py
[email protected]:~/so$ cat pkg/foo.py
print('executing module foo ...')
def bar():
print('bar')
모든 파이썬 쉘 조각은 파이썬 인터프리터 단일 대화 형 세션입니다. 사이에 내 자신의 해설을 추가하려면 블록을 여러 개로 나눕니다. 블록.
여기 내 파이썬 버전입니다.
Python 3.4.2 (default, Oct 8 2014, 10:45:20)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
다음 가져 오기 foo
__all__
때문에이 __init__.py
에 정의되어 있지 되어 가져올 수 없습니다.
>>> from pkg import *
>>> foo.bar()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
>>>
상기 동작은
https://docs.python.org/3/tutorial/modules.html#importing-from-a-package에서 파이썬 튜토리얼에서 설명되었다.__all__
가 정의되어 있지 않으면
는 문
from sound.effects import *
는 현재 이름 공간에 패키지sound.effects
에서 모든 서브 모듈을 가져올 수 없습니다; 패키지sound.effects
에 을 가져 왔고 (가능하면__init__.py
에 초기화 코드를 실행) 패키지에 정의 된 이름을 가져 오게합니다.
다음과 같은 수입품은 bar()
입니다. foo
을 가져올 수 없습니다.
>>> from pkg.foo import bar
executing module foo ...
>>> bar()
bar
>>> foo.bar()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
는 그러나 이상하게 이전 수입 후, 다음과 같은 가져 오기 __init__.py
에 정의되어 있지 않은 foo
도 __all__
경우 수입 을 끝납니다.
>>> from pkg import *
>>> foo.bar()
bar
왜 이런 일이 발생합니까?
''모듈'foo'를 가져올 것이다. '__all__'을 지정하면 같은 문제가 발생하지 않습니다. 내가 궁금한 점은'from pkg import *'가 문서와 일치하는지, 즉'foo'를 가져 오지 않지만'from pkg import * '의 두 번째 발생은 문서를 위반하고'foo'를 가져 오는 이유입니다. –