gpt4 book ai didi

python - importlib.import_module 在 python3.5 中有奇怪的行为

转载 作者:太空宇宙 更新时间:2023-11-04 00:19:27 24 4
gpt4 key购买 nike

具有相对模块名称的 importlib.import_module 有时会失败。

例如,我有这样一个包结构:

├── test0
│   ├── __init__.py
│   ├── test1.py
│   └── test2.py
├── test_impl.py

测试代码如下:

import importlib
import sys
print(sys.version_info)
def test_imp_module(module_name, pkgname):
try:
_m = importlib.import_module(module_name, pkgname)
print("import OK: module={}, pkg={}".format(module_name, pkgname))
except Exception as e:
print(e)

test_imp_module(".test1", "test0")
test_imp_module("test0.test1", "")
if __name__ == '__main__':
test_imp_module(".test1", "test0")
test_imp_module("test0.test1", "")

在 Python3.5 中它会在第一个测试中失败:

$ python3 test_impl.py 
sys.version_info(major=3, minor=5, micro=2, releaselevel='final', serial=0)
Parent module 'test0' not loaded, cannot perform relative import
import OK: module=test0.test1, pkg=
import OK: module=.test1, pkg=test0
import OK: module=test0.test1, pkg=

在 python3.6 中有效:

$ python3 test_impl.py 
sys.version_info(major=3, minor=6, micro=4, releaselevel='final', serial=0)
import OK: module=.test1, pkg=test0
import OK: module=test0.test1, pkg=
import OK: module=.test1, pkg=test0
import OK: module=test0.test1, pkg=

这是预期的还是错误?更新: Python2.7.12 与 3.6 具有相同的行为。

最佳答案

docs说:

importlib.import_module(name, package=None)

...

Changed in version 3.3: Parent packages are automatically imported.

因此,3.6.4 行为是正确的,而 3.5.2 行为是错误的。你好像在打#30876 ,并且该问题表示已在版本 5 micro 中修复,即 v3.5.5。

感谢 6 号房间的 vaultah finding the ticket .

关于python - importlib.import_module 在 python3.5 中有奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49787648/

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