Search code examples
pythonpython-3.xdistutils

What is the purpose of the __init__.py?


When creating a Python package, I am told to create a blank file called init.py. What I don't understand is why I need to create this file. The distutils build script doesn't modify it, so five builds later it's still blank. What is it's purpose?


Solution

  • It a signal to Python that the folder is a package, not just a folder. It also contains initialization code that is run when the package is imported into a script.

    See the docs on the subject for more. The most relevant extract:

    The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.