If you create a package consisting of several modules, you need to write the folder name (package name), file name (module name), function or class name to import, and the import statement becomes long. I want to shorten these. Or, I want to import with default settings across modules.
According to here
The imported module name is placed in the global symbol table of the importing module. The import statement has a variant that populates the name in a module directly into the symbol table of the module executing the import. (from..import ..)
So, if you import with __init__.py
, you can use the imported symbols in __init__.py
just by importing the package.
For example
/foo
- __init__.py
- bar.py
With the folder structure
$ cat bar.py
PIYO=100
$ cat __init__.py
from bar import PIYO
Then, foo.PIYO can be used with ʻimport foo`. It can be used to hide complex implementations within modules and provide libraries.
Recommended Posts