在Python 2.7中,是否需要显式导入子模块?

路易斯

此代码失败:

import setuptools.command
setuptools.command.install.install

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'install'

但这有效:

import setuptools.command.install
setuptools.command.install.install

<class setuptools.command.install.install at 0x7f2355911328>

其中installsetuptools命令子模块install模块的

Setuptools的版本是2.2,但是我尝试了一个虚拟的python项目,并且得到了相同的行为,因此我不确定这是特定于setuptools的。

在Ubuntu升级后(从python 2.7.4升级到2.7.6),我注意到了这一点。我确信第一个代码片段确实可以在升级前工作,但是在python发行说明中找不到任何相关的内容。

奇怪的是,这与os软件包的行为似乎有所不同

import os
os.path.join

<function join at 0x7f9f4be6fc80>

我的问题:使用其他程序包的子模块中的功能时,是否需要始终始终显式导入子模块?如果是这样,为什么这不影响os?否则,如何判断我是否需要这样做?

黑色的

os.path很特别 os模块,它注入os.pathsys.modules参见https://github.com/python-git/python/blob/715a6e5035bb21ac49382772076ec4c630d6e960/Lib/os.py#L119

因此,通常,您始终需要导入子模块。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章