programing tip

Python 3.3 이상에서 패키지에 __init__.py가 필요하지 않습니까?

itbloger 2020. 6. 22. 08:04
반응형

Python 3.3 이상에서 패키지에 __init__.py가 필요하지 않습니까?


Python 3.5.1을 사용하고 있습니다. https://docs.python.org/3/tutorial/modules.html#packages 에서 문서와 패키지 섹션을 읽었습니다.

이제 다음과 같은 구조가 있습니다.

/home/wujek/Playground/a/b/module.py

module.py:

class Foo:
    def __init__(self):
        print('initializing Foo')

이제는 /home/wujek/Playground:

~/Playground $ python3
>>> import a.b.module
>>> a.b.module.Foo()
initializing Foo
<a.b.module.Foo object at 0x100a8f0b8>

마찬가지로, 이제 집에서 다음과 Playground같은 슈퍼 폴더가 있습니다 :

~ $ PYTHONPATH=Playground python3
>>> import a.b.module
>>> a.b.module.Foo()
initializing Foo
<a.b.module.Foo object at 0x10a5fee10>

실제로 모든 종류의 작업을 수행 할 수 있습니다.

~ $ PYTHONPATH=Playground python3
>>> import a
>>> import a.b
>>> import Playground.a.b

왜 이것이 작동합니까? 내가있을 필요하지만 __init__.py모두에서 파일 (비어있는 작업 것) ab대한 module.py임포트 될 때까지 파이썬 경로 지점 Playground폴더?

이것은 파이썬 2.7에서 변경된 것으로 보입니다.

~ $ PYTHONPATH=Playground python
>>> import a
ImportError: No module named a
>>> import a.b
ImportError: No module named a.b
>>> import a.b.module
ImportError: No module named a.b.module

__init__.py둘 다 ~/Playground/a함께 ~/Playground/a/b잘 작동합니다.


Python 3.3+에는 파일 없이 패키지를 만들 수있는 암시 적 네임 스페이스 패키지__init__.py있습니다.

암시 적 네임 스페이스 패키지를 허용한다는 것은 __init__.py파일 제공 요구 사항 이 완전히 삭제 되어 영향을받을 수 있음 을 의미합니다 .

__init__.py파일을 사용 하는 오래된 방법은 여전히 Python 2에서 같이 작동합니다.


중대한

@ Mike의 대답은 정확하지만 너무 정확하지 않습니다. Python 3.3 이상 파일 없이 패키지를 만들 수있는 암시 적 네임 스페이스 패키지지원한다는 것은 사실입니다 __init__.py.

그러나 이것은 EMPTY__init__.py 파일 에만 적용됩니다 . 따라서 EMPTY__init__.py 파일은 더 이상 필요하지 않으므로 생략 할 수 있습니다. 패키지 또는 해당 모듈 또는 하위 패키지를 가져올 때 특정 초기화 스크립트를 실행하려면 여전히 __init__.py파일이 필요 합니다. 이것은 왜 유용한 지 궁금한 경우 파일을 사용하여 추가 초기화를 수행 하려는 이유에 대한 훌륭한 스택 오버플로 답변 입니다 __init__.py.

디렉토리 구조 예 :

  parent_package/
     __init__.py            <- EMPTY, NOT NECESSARY in Python 3.3+
     child_package/
          __init__.py       <- STILL REQUIRED if you want to run an initialization script
          child1.py
          child2.py
          child3.py

parent_package/child_package/__init__.py:

print("from parent")

실시 예

아래 예제 child_package는 모듈 중 하나를 가져올 때 초기화 스크립트가 실행되는 방법을 보여줍니다 .

예 1 :

from parent_package import child_package  # prints "from parent"

예 2 :

from parent_package.child_package import child1  # prints "from parent"

If you have setup.py in your project and you use find_packages() within it, it is necessary to have an __init__.py file in every directory for packages to be automatically found.

Packages are only recognized if they include an __init__.py file

Docs


I would say that one should omit the __init__.py only if one wants to have the implicit namespace package. If you don't know what it means, you probably don't want it and therefore you should continue to use the __init__.py even in Python 3.

참고URL : https://stackoverflow.com/questions/37139786/is-init-py-not-required-for-packages-in-python-3-3

반응형