I'm using Python 2.7 and have the following files:
./__init__.py
./aoeu.py
__init__.py
has the following contents:
aoeu aoeuaoeu aoeuaoeuaoeu
so I would expect running aoeu.py to error when Python tries to load __init__.py
, but it doesn't. The behavior is the same whether PYTHONPATH is set to '.' or unset.
What's going on?
__init__.py can be empty, as long as it exists. It indicates that the directory should be regarded as a package.
The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , unintentionally hiding valid modules that occur later on the module search path.
In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.
Here are a few reasons why a module may not be found: you do not have the module you tried importing installed on your computer. you spelled a module incorrectly (which still links back to the previous point, that the misspelled module is not installed)...for example, spelling numpy as numpys during import.
__init__.py
makes the enclosing directory a package. It won't be executed unless you actually try to import the package directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With