Suppose I have a package structure like
pkg __init__.py module __init__.py a.py b.py
Suppose, there is a function func in a.py. I want to create a library, that can import func directly from pkg.
from pkg import func
How can I achieve this?
Advertisement
Answer
You can configure this via the __init__.py
.
pkg/__init__.py
from .module.a import func
That way when pkg
is accessed, the __init__.py
would be loaded thus allowing direct access to pkg.func
This is as documented:
A regular package is typically implemented as a directory containing an
__init__.py
file. When a regular package is imported, this__init__.py
file is implicitly executed, and the objects it defines are bound to names in the package’s namespace. The__init__.py
file 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.