Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the __init__.py really not necessary for python 3.7 packages?

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?

like image 823
Mazimia Avatar asked Jan 21 '20 09:01

Mazimia


People also ask

Is __ init __ needed in Python 3?

@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.

Do Python packages need init?

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).

Why do I need __ init __ py?

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.

What is the use of file __ init __ py in a package even when it is empty?

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.


1 Answers

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.

like image 147
Théo Vermersch Avatar answered Oct 18 '22 03:10

Théo Vermersch