开发者

Is there a better way to determine something is a module in python

I have the name of an 'thing' in python. I want to check if this 'thing' is a module or not. I can do it with the below code:

mod = eval(module_name)
pri开发者_开发知识库nt inspect.ismodule(mod)

I don't like the idea of calling eval. Is there a better way to get from the module_name, which is a string, to the actual module object?


Better yet, forget about __import__'ing it, and just see if it exists. :)

Now, I don't know if this is actually much faster, however it's what I would do. __import__ at the core uses imp.find_module() anyways.

import imp
try:
    imp.find_module('module')
except ImportError:
    import sys
    sys.exit('No such module')


Just try build-in __import__ function:

>>> __import__('aaa')

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    __import__('aaa')
ImportError: No module named aaa
>>> __import__('os')
<module 'os' from 'C:\Python26\lib\os.pyc'>

So you code might look like next:

try:
    __import__(mod_name)
    print 'Such a module exists'
except ImportError:
    print 'No such module'


import datetime
from types import ModuleType

print type(datetime) == ModuleType

Edit: Sorry, misread the question. "name of a thing" is not what this example is using.


Use dir() on the 'thing':

dir(something)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜