Can someone help and clarify, when using import
command(s), at which moment the __init__.py files in various package directory(s) is/are executed?
import
command?import
command?It's evaluated on first module import. On next imports, interpreter detects that module was already loaded and simply returns reference to it. There is no need to re-execute code.
Quoting The import system:
On caching modules:
The first place checked during import search is sys.modules. This mapping serves as a cache of all modules that have been previously imported, including the intermediate paths. So if foo.bar.baz was previously imported, sys.modules will contain entries for foo, foo.bar, and foo.bar.baz. Each key will have as its value the corresponding module object.
During import, the module name is looked up in sys.modules and if present, the associated value is the module satisfying the import, and the process completes. However, if the value is None, then an ImportError is raised. If the module name is missing, Python will continue searching for the module.
On executing __init__
when importing:
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.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With