gpt4 book ai didi

python - __init__.py 中的局部作用域与相对导入

转载 作者:行者123 更新时间:2023-12-03 16:16:21 25 4
gpt4 key购买 nike

我注意到 asyncio/init.py from python 3.6使用以下构造:

from .base_events import *

...

__all__ = (base_events.__all__ + ...)
base_events源代码中的任何地方都没有导入符号,但模块仍然包含它的局部变量。
我用下面的代码检查了这个行为,放入 __init__.py带假人 test.py在它的旁边:
test = "not a module"
print(test)

from .test import *
print(test)

not a module
<module 'testpy.test' from 'C:\Users\MrM\Desktop\testpy\test.py'>


这意味着 test使用星形导入后变量被遮蔽。
我摆弄了一下,结果是 它不一定是明星进口 ,但它必须在 __init__.py 内, 它必须是相对的。否则,模块对象不会被分配到任何地方。
如果没有赋值,则从不是 __init__.py 的文件运行上述示例将引发 NameError .
这种行为来自哪里?这是否已在某处的导入系统规范中进行了概述? __init__.py 背后的原因是什么|必须以这种方式特别吗?不是 in the reference ,或者至少我找不到它。

最佳答案

此行为在 The import system 中定义。文档部分 5.4.2 Submodules

When a submodule is loaded using any mechanism (e.g. importlib APIs,the import or import-from statements, or built-in import()) abinding is placed in the parent module’s namespace to the submoduleobject. For example, if package spam has a submodule foo, afterimporting spam.foo, spam will have an attribute foo which is bound tothe submodule.


包命名空间包括在 __init__.py 中创建的命名空间。加上导入系统添加的附加功能。原因是为了命名空间的一致性。

Given Python’s familiar name binding rules this might seem surprising,but it’s actually a fundamental feature of the import system. Theinvariant holding is that if you have sys.modules['spam'] andsys.modules['spam.foo'] (as you would after the above import), thelatter must appear as the foo attribute of the former.

关于python - __init__.py 中的局部作用域与相对导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65282049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com