Python 没有 from 子句的 import 语句导入 class 不是模块
Python import statement without a from clause imports a class not a module
如下面的简单测试用例所示,当 class 被导入包的 __init__.py
时,import 语句导入 class 而不是同名模块.
这是预期的行为还是错误?无论哪种情况,如果任何人都可以引用任何相关文档或错误报告,那将会很有帮助。如果是错误,了解预期行为是什么将很有用:应该导入模块 pkg.a,还是应该引发错误?
包布局
C:\...\imp_test
|
\---pkg
a.py
__init__.py
文件
__init__.py
from .a import a
a.py
class a:
pass
结果
C:\...\imp_test> python
Python 3.7.1 (default, Dec 10 2018, 22:54:23)
[MSC v.1915 64 bit (AMD64)] :: Anaconda custom (64-bit) on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.a
>>> type(pkg.a)
<class 'type'>
>>> var = pkg.a()
>>>
更新:
这是pkg中绑定a的模块和pkg中绑定a的变量之间的命名空间冲突。
这是所描述的预期行为 here
旧:
我相信这是因为导入语句使用的查找器。
finder 会在模块路径之前先搜索包,因为它会立即找到匹配它的路径 returns.
我查看了 python 导入文档 here 并找到了这个小片段
When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned.
如果要强制导入模块,可以使用 import_module 函数
import importlib
a = importlib.import_module('pkg.a')
如下面的简单测试用例所示,当 class 被导入包的 __init__.py
时,import 语句导入 class 而不是同名模块.
这是预期的行为还是错误?无论哪种情况,如果任何人都可以引用任何相关文档或错误报告,那将会很有帮助。如果是错误,了解预期行为是什么将很有用:应该导入模块 pkg.a,还是应该引发错误?
包布局
C:\...\imp_test
|
\---pkg
a.py
__init__.py
文件
__init__.py
from .a import a
a.py
class a:
pass
结果
C:\...\imp_test> python
Python 3.7.1 (default, Dec 10 2018, 22:54:23)
[MSC v.1915 64 bit (AMD64)] :: Anaconda custom (64-bit) on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.a
>>> type(pkg.a)
<class 'type'>
>>> var = pkg.a()
>>>
更新:
这是pkg中绑定a的模块和pkg中绑定a的变量之间的命名空间冲突。 这是所描述的预期行为 here
旧:
我相信这是因为导入语句使用的查找器。 finder 会在模块路径之前先搜索包,因为它会立即找到匹配它的路径 returns.
我查看了 python 导入文档 here 并找到了这个小片段
When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned.
如果要强制导入模块,可以使用 import_module 函数
import importlib
a = importlib.import_module('pkg.a')