python - python 在什么时候以及多久执行一次 __init__.py 文件

标签 python python-import

有人可以帮忙澄清一下,当使用 import 命令时,此时会执行各种包目录中的 __init__.py 文件?

  1. 对于每个包含的模块?
  2. 仅在第一个 import 命令中执行一次?
  3. 对于每个 import 命令?

最佳答案

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

引用 The import system :

关于缓存模块:

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.

关于python - python 在什么时候以及多久执行一次 __init__.py 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39452319/

相关文章:

python - Python中导入azure.servicebus错误

python - 区分同名的 Python 模块/安装不同的名称?

使用nose进行测试的Python导入-在当前包之上导入模块的最佳实践是什么

python - 运行时错误 : PyTorch does not currently provide packages for PyPI

python - 根据重新排列的重复项对 pandas 数据框进行切片(或如何删除重新排列的重复项)

Python:将浮点范围[0.0,1.0]映射到颜色范围[红色,绿色]?

python - 找出引发 `ImportError` 时真正出错的地方

python - 为什么两个链接的 gtk 切换按钮会出现运行时错误?

python - Python 中使用 'with' 语句的 IndexError 消息

python - 来自其他文件的工作目录中的 execfile