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

时间:2014-07-28 10:22:30

标签: python 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>

其中 install setuptools 命令子模块的 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>

我的问题:当使用位于不同包的子模块中的功能时,是否需要始终显式导入子模块?如果是这样,为什么这不影响操作系统?否则,如何判断我是否需要这样做?

1 个答案:

答案 0 :(得分:0)

os.path很特别。在os模块中,它会将os.path注入sys.modules。见https://github.com/python-git/python/blob/715a6e5035bb21ac49382772076ec4c630d6e960/Lib/os.py#L119

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