Many tutorials seem to imply that the typical __init__.py file in a package is empty. But this never works for me. Typically, I start a project by writing a series of .py modules in a directory. When I decide my project could be useful in other projects I'm working on, I try to turn it into a package by adding an empty __init__.py file. But when I try to import that package, I don't have access to any of the modules I wrote unless I import them in the __init__.py file.
Is this normal? How is a package with an empty __init__.py file structured to give access to its modules when you import it?
Videos
I've been looking into some projects for some opensource software i use and noticed a few of them have empty __init__.py files (for example https://github.com/netbox-community/netbox/blob/develop/netbox/core/__init__.py)
Whats the point of these?
It used to be a required part of a package (old, pre-3.3 "regular package", not newer 3.3+ "namespace package").
Here's the documentation.
Python defines two types of packages, regular packages and namespace packages. Regular packages are traditional packages as they existed in Python 3.2 and earlier. A regular package is typically implemented as a directory containing an
__init__.pyfile. When a regular package is imported, this__init__.pyfile is implicitly executed, and the objects it defines are bound to names in the package’s namespace. The__init__.pyfile can contain the same Python code that any other module can contain, and Python will add some additional attributes to the module when it is imported.
But just click the link, it contains an example, more information, and an explanation of namespace packages, the kind of packages without __init__.py.
Files named __init__.py are used to mark directories on disk as Python package directories.
If you have the files
mydir/spam/__init__.py
mydir/spam/module.py
and mydir is on your path, you can import the code in module.py as
import spam.module
or
from spam import module
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.
The __init__.py file is usually empty, but can be used to export selected portions of the package under more convenient name, hold convenience functions, etc.
Given the example above, the contents of the init module can be accessed as
import spam
This answer is based on this webpage.