Search code examples
pythonintrospection

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)
print 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?


Solution

  • 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'