__init__.py에 코드 추가
django의 모델 시스템이 어떻게 작동하는지 살펴보고 있는데 이해가 안되는 부분을 발견했습니다.
__init__.py
현재 디렉토리가 패키지임을 지정하기 위해 빈 파일을 생성한다는 것을 알고 있습니다 . 그리고 __init__.py
import *가 제대로 작동하도록 몇 가지 변수를 설정할 수 있습니다 .
그러나 django는 from ... import ... 문을 추가하고 __init__.py
. 왜? 이로 인해 상황이 복잡해 보이지 않습니까? 이 코드가 필요한 이유가 __init__.py
있습니까?
__init__.py
포함 된 패키지 (디렉토리)를 가져올 때 모든 가져 오기를 사용할 수 있습니다.
예:
./dir/__init__.py
:
import something
./test.py
:
import dir
# can now use dir.something
편집 : 언급하는 것을 잊었습니다 __init__.py
. 해당 디렉토리에서 모듈을 처음 가져올 때 코드가 실행됩니다. 따라서 일반적으로 패키지 수준 초기화 코드를 넣는 것이 좋습니다.
EDIT2 : dgrant는 내 예에서 가능한 혼란을 지적했습니다. In __init__.py
import something
은 패키지에서 필요하지 않은 모든 모듈을 가져올 수 있습니다. 예를 들어으로 바꿀 수 있습니다 import datetime
. 그러면 최상위 수준 test.py
에서 다음 코드 조각이 모두 작동합니다.
import dir
print dir.datetime.datetime.now()
과
import dir.some_module_in_dir
print dir.datetime.datetime.now()
결론은에서 할당 된 모든 이름 __init__.py
, 가져온 모듈, 함수 또는 클래스에 관계없이 패키지 또는 패키지의 모듈을 가져올 때마다 패키지 네임 스페이스에서 자동으로 사용할 수 있습니다.
그것은 단지 개인적인 선호 일 뿐이며 파이썬 모듈의 레이아웃과 관련이 있습니다.
라는 모듈이 있다고 가정 해 보겠습니다 erikutils
. 거기는 모듈 될 수 있다는 두 가지 방법이 있습니다, 하나는라는 파일이 erikutils.py을 당신에 sys.path
또는 당신이라는 디렉토리가 erikutils 온을 sys.path
빈과 __init__.py
그 안에 파일. 그럼 당신이 전화 모듈의 무리가 있다고 가정하자 fileutils
, procutils
, parseutils
그리고 당신이 그 미만의 서브 모듈이되고 싶어요 erikutils
. 따라서 fileutils.py , procutils.py 및 parseutils.py 라는 .py 파일을 만듭니다 .
erikutils
__init__.py
fileutils.py
procutils.py
parseutils.py
어쩌면 당신은하지에 속하지 않는 몇 가지 기능을 가지고 fileutils
, procutils
또는 parseutils
모듈을. 라는 새 모듈을 만들고 싶지 않다고 가정 해 보겠습니다 miscutils
. 그리고 다음과 같이 함수를 호출 할 수 있기를 원합니다.
erikutils.foo()
erikutils.bar()
하기보다는
erikutils.miscutils.foo()
erikutils.miscutils.bar()
따라서 erikutils
모듈은 파일이 아니라 디렉토리 이기 때문에 파일 내부에 함수를 정의해야 __init__.py
합니다.
In django, the best example I can think of is django.db.models.fields
. ALL the django *Field classes are defined in the __init__.py
file in the django/db/models/fields directory. I guess they did this because they didn't want to cram everything into a hypothetical django/db/models/fields.py model, so they split it out into a few submodules (related.py, files.py, for example) and they stuck the made *Field definitions in the fields module itself (hence, __init__.py
).
Using the __init__.py
file allows you to make the internal package structure invisible from the outside. If the internal structure changes (e.g. because you split one fat module into two) you only have to adjust the __init__.py
file, but not the code that depends on the package. You can also make parts of your package invisible, e.g. if they are not ready for general usage.
Note that you can use the del
command, so a typical __init__.py
may look like this:
from somemodule import some_function1, some_function2, SomeObject
del somemodule
Now if you decide to split somemodule
the new __init__.py
might be:
from somemodule1 import some_function1, some_function2
from somemodule2 import SomeObject
del somemodule1
del somemodule2
From the outside the package still looks exactly as before.
참고URL : https://stackoverflow.com/questions/119167/adding-code-to-init-py
'program tip' 카테고리의 다른 글
IntelliJ가 편집기 탭을 자동으로 닫지 않도록하려면 어떻게해야합니까? (0) | 2020.09.22 |
---|---|
자체 서명 된 SSL 인증서가 잘못되었습니다. "주체 대체 이름 누락" (0) | 2020.09.22 |
setTimeout ()에 남은 시간을 찾으십니까? (0) | 2020.09.22 |
CMAKE_INSTALL_PREFIX 사용 방법 (0) | 2020.09.22 |
파이썬의 "이 유니 코드를위한 최고의 ASCII"데이터베이스는 어디에 있습니까? (0) | 2020.09.22 |