Do I need an __init__.py
file in a python directory?
If it's your main project directory and your project is not just a package, no. If the directory is a package, yes.
If you're coming from python 2, the above seems obvious, but if you started
programming with python 3 you might have noticed that things seem to work if
you don't put an __init__.py
file in a directory that is a package. And then
be suprised when tools like mypy fail to read your codebase.
So, let's start with the official documentation. In the python documentation for packages at https://docs.python.org/3/tutorial/modules.html#packages we find the authoritative answer "The init.py files are required to make Python treat directories containing the file as packages."
So, why does the python 3 interpreter still work without __init__.py
files?
The answer comes from PEP-420 (namespace packages). In that case the interpreter assumes that it's dealing with a directory that has a series of namespace packages. End result is that it all seems to work until it doesn't and you spend some time debugging why a certain tool like pytest or mypy don't work as you expect.