问题
I'm using python 2.6 and I'm seeing somewhat weird behavior with the dir()
function. I'm trying to import all the modules from a directory/package for a unittest but when I do a dir()
on on the folder, I don't get all the modules in that directory.
Sample directory structure:
|-mod_dir\
|---__init__.py
|---modA.py
|---modB.py
|---modC.py
|
|-mod_tests\
|---__init__.py
|---test.py
Sample test.py:
import mod_dir
for obj in dir(mod_dir):
print obj
Unfortunately, at this point I only get something like:
modA
__all__
__builtins__
__doc__
__file__
__name__
__package__
__path__
Any ideas as to why the others aren't appearing here? I don't think it matters, but the __init__.py
file in the mod_dir is empty. I've tried setting the __all__
variable but it has no effect. If it does matter, however, I'm using this in WinXp with pydev in eclipse.
Context:
Each module under mod_dir has a unittest in it and I'm trying to include them in a unittest suite within test.py. I'm aware of nose and other methods like this one, but I'm more interested in why dir isn't displaying everything.
回答1:
I believe it does matter that the __init__.py
file is empty.
Try this in the __init__.py
:
import modA
import modB
import modC
From the python docs, dir should not be used for this (see the Note at the bottom of the dir
section). It's not rigorous enough, and mainly used in the interactive prompt.
来源:https://stackoverflow.com/questions/7193850/python-dir-not-displaying-all-modules-in-a-package