Python dir() 不显示包中的所有模块

标签 python unit-testing module dir

我正在使用 python 2.6,并且我发现 dir() 有一些奇怪的行为功能。我试图从目录/包中导入所有模块进行单元测试,但是当我执行 dir() 时在文件夹上,我没有获得该目录中的所有模块。

示例目录结构:

|-mod_dir\
|---__init__.py
|---modA.py
|---modB.py
|---modC.py
|
|-mod_tests\
|---__init__.py
|---test.py

示例 test.py:

import mod_dir

for obj in dir(mod_dir):
   print obj

不幸的是,此时我只得到如下内容:

modA
__all__
__builtins__
__doc__
__file__
__name__
__package__
__path__

关于为什么其他人没有出现在这里有什么想法吗?我认为这并不重要,但是 __init__.py mod_dir 中的文件为空。我尝试设置 __all__变量,但没有效果。不过,如果它确实重要,我会在 WinXp 中使用它,并在 Eclipse 中使用 pydev。

上下文:

mod_dir 下的每个模块都有一个单元测试,我试图将它们包含在 test.py 中的单元测试套件中。我知道 Nose 和其他方法,如 this一,但我更感兴趣的是为什么 dir 没有显示所有内容。

最佳答案

我相信 __init__.py 文件为空确实很重要。

__init__.py中尝试一下:

import modA
import modB
import modC

来自 python 文档,dir should not be used for this (请参阅 dir 部分底部的注释)。不够严谨,主要用在交互提示上。

关于Python dir() 不显示包中的所有模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7193850/

相关文章:

Python:以类似表格的格式将字典转储到 csv 文件的列中

python - 将 gevent 与 python xmlrpclib 一起使用

Angular - fixture.debugElement.query(By.directive(IsRouteDirective) 找不到宿主元素

javascript - 模拟 - 在调用构造函数之前设置属性

java - @在HSQL数据库中生成

error-handling - Ansible:模拟一个 "passed when"模块

Python 和 py2exe - 隐式导入模块

Perl - Spreadsheet::WriteExcel 函数解释

python - Google Analytics 管理 API 插入属性 - 权限不足 403

用于复杂列表和整数组合的 python 正则表达式