What should you put into your __init__.py?
Perhaps you already know that a python package is a directory which contains a __init__.py file
In this article we will solve the mystery around the __init__.py
For this article let’s assume the following project structure:
Empty init file
Sometimes doing nothing isn’t so bad at all. You can of course leave the init file empty
That means that you have to import func_a from module_a in package_a in the follow way from your main.py
from package_a.module_a import func_a func_a()
Import * in init
If you want to avoid giving the the full path to your function you can place an import statement in the __init__.py as well
from .module_b import *
In your main.py you don’t have to mention the module name anymore:
from package_b import func_b func_b()
In addition to adding an import in your init file you can also add the __all__ list declaration
With this construct you can decide which functions from your modules will be imported when you use the “import *” semantic:
__all__ = ['func_c'] from .module_c import *
from package_c import * func_c() # working func_d() # not working! Unresolved reference 'func_d'
This is excellent for API design to describe which functions shall be exposed to the user of the package.