Thursday 28 December 2017

Is __init__.py not required for packages in Python 3.3+

itemprop="text">

I am using Python 3.5.1. I read the
document and the package section here: href="https://docs.python.org/3/tutorial/modules.html#packages">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
0x100a8f0b8>


Similarly,
now in home, superfolder of
Playground:



~
$ PYTHONPATH=Playground python3
>>> import
a.b.module
>>> a.b.module.Foo()
initializing
Foo
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.



Answer




Python 3.3+ has href="https://www.python.org/dev/peps/pep-0420/" rel="noreferrer">Implicit Namespace
Packages that allow it 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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...