1

Is there any case (testing or whatever etc...) or usefulness to have a folder containing python files without the __init__.py file? i.e:

   project/
           run.py
           package1/
                   file1.py
                   file2.py

instead of:

   project/
           run.py
           package1/
                    __init__.py
                    file1.py
                    file2.py

I ask this because I have seen some projects with folders (that contain python files) with and without the __init__.py file so I was wondering if there is a reason for this to happen. I also have seen some people complaining about Pylance in Visual Code Studio missing importing own modules but adding the __init__.py file in the folder containing the module seems to solve that issue (in case you have this issue try this ;) ).

From this thread Is __init__.py not required for packages in Python 3.3+ and other sources I have seen that there are namespace packages in python that do not have the __init__.py file. However if I am not mistaken this only applies when you are creating a folder containing ONLY another folder a not python files.

So from all this my take away message for good practices when doing a python project is:

  • add a __init__.py file to all folders containing python files
  • folders that only contain a folder(s) and no python files should not have the __init__.py (this is a namespace package)
  • folders that only contain images or other no-python files/documents should not have the __init__.py

Is this correct?

quamrana
  • 37,849
  • 12
  • 53
  • 71
alect
  • 103
  • 1
  • 6
  • Welcome to Stack Overflow. We generally [don't take](https://stackoverflow.com/help/dont-ask) questions about "best practices" or what you "should" do, only about a) what works; b) what best satisfies some *objective* metric such as performance. – Karl Knechtel Jan 12 '22 at 12:11
  • Thanks for the info. Although best practices is a subjective topic I think it is an important one after all they help avoiding situations where things don't work and make things more maintainable (and meaningful). Stack Overflow being such a big reference for software developers I think I would be nice to have a section dedicated to it. – alect Jan 12 '22 at 15:10

0 Answers0