6

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?

Mazimia
  • 192
  • 2
  • 11
  • Perhaps this answers your question? https://stackoverflow.com/questions/37139786/is-init-py-not-required-for-packages-in-python-3-3 – Lapis Rose Jan 21 '20 at 09:15
  • No it doesn't. The answer there says when the \__init__.py file is empty it could be removed. In my case I had import errors and was debugging for hours until I decided to add the empty \__init__.py file in the test folder and that solved the problem. – Mazimia Jan 21 '20 at 09:24
  • might be a tough ask, but could you prepare a [mcve]? – Paritosh Singh Jan 21 '20 at 09:34
  • 1
    @Mazimia actually the answers on that question say that `__init__.py` is sometimes required, even empty ones, even in newer versions of Python. – Flimm Jan 11 '22 at 13:26
  • Does this answer your question? [Is \_\_init\_\_.py not required for packages in Python 3.3+](https://stackoverflow.com/questions/37139786/is-init-py-not-required-for-packages-in-python-3-3) – Flimm Jan 11 '22 at 13:27

1 Answers1

11

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.

Théo Vermersch
  • 164
  • 1
  • 9
  • 10
    If some tools like pytest and unittest still needs the \__init__.py file then it's not totally correct to say it's not necessary for packages anymore. – Mazimia Jan 22 '20 at 09:24