At which moment and how often are executed the __init__.py files by python
<p>Can someone help and clarify, when using <code>import</code> command(s), at which moment the <em>__init__.py</em> files in various package directory(s) is/are executed?</p>

<ol>
<li>For each included module?</li>
<li>Only once at 1st <code>import</code> command?</li>
<li>For each <code>import</code> command?</li>
</ol>

<p>It's evaluated on first module import. On next imports, intrpreter detects that module was already loaded and simply returns reference to it. There is no need to re-execute code.</p>

<p>Quoting <a href="https://docs.python.org/3/reference/import.html" rel="nofollow">The import system</a>:</p>

<p>On caching modules:</p>

<blockquote>
  <p>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.</p>
  
  <p><strong>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.</strong> However, if the value is None, then an ImportError is raised. If the module name is missing, Python will continue searching for the module.</p>
</blockquote>

<p>On executing <code>__init__</code> when importing:</p>

<blockquote>
  <p>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 <strong>init</strong>.py file. <strong>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.</strong></p>
</blockquote>

python python-import