How to check submodules in Python with hasattr
At runtime, the Python code gets the name of a submodule to load, which I don't know before. Now, I want to check, if this submodule exists inside an existing module. Consider this structure, where foo
and bar
can be specified:
master/
|
|- __init__.py
|
|- foo/
| |
| |- __init__.py
|
|- bar/
|
|- __init__.py
Now, usually I do this, which works for defs and variables:
import master
unknown_submodule = "foo"
if hasattr(master, unknown_submodule):
pass # all's well
or I'm catching the AttributeError, which works equally.
However, with the above file structure, I'm not able to bring this approach up and working. hasattr()
return开发者_运维知识库s always False (that is, there is always an AttributeError thrown).
If I look at dir(master)
, I see this output:
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
and even explicitly specifying __all__
in master/__init__.py
doesn't help, but changes the dir() to
['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
Any idea, what I'm doing wrong, or if there is a way to achieve these kinds of tests? (Btw: Python 2.6 on Win/Cygwin, if that's of any interest)
Submodules are not attributes of their parent modules unless stated explicitly. Simply try to import the module and catch ImportError
:
try:
__import__("os.peth", fromlist=[os])
except ImportError:
pass
I recently had to check submodule existence and since I'm using python 3.4.1, I'm giving a new answer to the question:
In python 3.4.1 you can use importlib.util.find_spec(name, package=None)
(https://docs.python.org/3.4/library/importlib.html#importlib.util.find_spec)
import importlib
module_exists = importlib.util.find_spec('path.to.my.module')
That easy =)
you can do
try:
import module.submodule
except ImportError:
print 'failed or whatever'
精彩评论