在哪个时刻以及python执行__init__.py文件的频率

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

当使用import命令时,是否有人能帮助和澄清,在什么时候执行不同包目录中的init_uuuuuuy文件?

  • 对于每个包含的模块?
  • 只有一次在第一个import命令下?
  • 对于每个import命令?

  • 它是在第一个模块导入时评估的。在下一次导入时,解释器检测到模块已经加载,并简单地返回对它的引用。不需要重新执行代码。

    引用进口系统:

    在缓存模块上:

    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.

    进口时执行__init__时:

    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.