Recently I created a flask application and decided to add a test folder outside the application folder (both the app and test folders are in the same directory). All the implementations I would be testing for are contained in packages and modules created in the app folder.
Having the __init__.py file in both folders work just fine as expected. However when I remove the __init__.py file from the test folder, I start to experience moduleImportError. Python doc says that the __init__.py file is no longer a requirement for packages in python 3.3+ but in my case here, seems it's a requirement. Can someone explain why it's so?
@Mike's answer is correct but too imprecise. It is true that Python 3.3+ supports Implicit Namespace Packages that allows it 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.
Although Python works without an __init__.py file you should still include one. It specifies that the directory should be treated as a package, so therefore include it (even if it is empty).
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.
If you remove the __init__.py file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail. Leaving an __init__.py file empty is considered normal and even a good practice, if the package's modules and sub-packages do not need to share any code.
Quick answer, Yes, thanks to the Implicit Namespace Packages you dont need __init__.py
files anymore.
But some tools of the standart library including unittest or setup tools still needs __init__.py
files.
In most of the case I recommend the following project arborescence:
setup.py
src/
mypkg/
__init__.py
app.py
view.py
tests/
__init__.py
foo/
__init__.py
test_view.py
bar/
__init__.py
test_view.py
Top pakage src
and root folder does not needs __init__.py
files.
Every other submodules need a __init__.py
file.
By following this rule most of tools succesfully discover modules including unittest, pytest and setuptools.
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