Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

At which moment and how often are executed the __init__.py files by python

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?

  1. For each included module?
  2. Only once at 1st import command?
  3. For each import command?
like image 921
Sharphawk Avatar asked Sep 12 '16 14:09

Sharphawk


1 Answers

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.

like image 142
Łukasz Rogalski Avatar answered Nov 04 '22 10:11

Łukasz Rogalski