.py not required for packages in Python 3?

I am using Python 3.5.1. I read the document and the package section here: https://docs.python.org/3/tutorial/modules.html#packages

Now, I have the following structure:

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

module.py :

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

Now, while in /home/wujek/Playground :

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

Similarly, now in home, superfolder of Playground :

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

Actually, I can do all kinds of stuff:

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

Why does this work? I though there needed to be __init__.py files (empty ones would work) in both a and b for module.py to be importable when the Python path points to the Playground folder?

This seems to have changed from Python 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

With __init__.py in both ~/Playground/a and ~/Playground/a/b it works fine.


Python 3.3+ has Implicit Namespace Packages that allow to create a packages without an __init__.py file.

Allowing implicit namespace packages means that the requirement to provide an __init__.py file can be dropped completely , and affected ... .

The old way with __init__.py files still works as in Python 2.


@Mike's answer is correct but too imprecise. It is true that Python 3.3+ supports Implicit Namespace Packages that allows to create a package without an __init__.py file.

This however, ONLY applies to EMPTY __init__.py files. So EMPTY __init__.py files are no longer necessary and can be omitted. If you want to import modules into a package you still require an __init__.py file listing all the imports.

Directory Structure Example:

  parent_package/
     __init__.py            <- EMPTY, NOT NECESSARY in Python 3.3+
     child_package/
          __init__.py       <- STILL REQUIRED to import all child modules
          child1.py
          child2.py
          child3.py

__init__ file in child_package :

import child1
import child2
import child3
链接地址: http://www.djcxy.com/p/9330.html

上一篇: 从命令运行一个Ruby库

下一篇: .py在Python 3中不需要包?