Check if a parameter is a Python module?

PythonTypes

Python Problem Overview


How can I (pythonically) check if a parameter is a Python module? There's no type like module or package.

>>> os
<module 'os' from '/usr/lib/python2.6/os.pyc'>

>>> isinstance(os, module)
Traceback (most recent call last):
  File "/usr/lib/gedit-2/plugins/pythonconsole/console.py", line 290, in __run
    r = eval(command, self.namespace, self.namespace)
  File "<string>", line 1, in <module>
NameError: name 'module' is not defined

I can do this:

>>> type(os)
<type 'module'>    

But what do I compare it to? :(

I've made a simple module to quickly find methods in modules and get help texts for them. I supply a module var and a string to my method:

def gethelp(module, sstring):

    # here i need to check if module is a module.

    for func in listseek(dir(module), sstring):
        help(module.__dict__[func])

Of course, this will work even if module = 'abc': then dir('abc') will give me the list of methods for string object, but I don't need that.

Python Solutions


Solution 1 - Python

from types import ModuleType

isinstance(obj, ModuleType)

Solution 2 - Python

>>> import inspect, os
>>> inspect.ismodule(os)
True

Solution 3 - Python

This seems a bit hacky, but:

>>> import sys
>>> import os
>>> type(os) is type(sys)
True

Solution 4 - Python

A mix of @Greg Hewgill and @Lennart Regebro answers:

>>> from types import ModuleType
>>> import os
>>> type(os) is ModuleType
True

Solution 5 - Python

Flatten the module to a string and check if it starts with '<module '

import matplotlib
foobarbaz = "some string"
print(str(matplotlib).startswith("<module "))     #prints True
print(str(foobarbaz).startswith("<module "))      #prints False

Drawback being this could collide with a python string that starts with the text '<module' You could try to classify it more strongly with a regex.

Solution 6 - Python

Two ways,you could not import any modules:

  • type(os) is type(__builtins__)
  • str(type(os)).find('module')>-1

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionculebr&#243;nView Question on Stackoverflow
Solution 1 - PythonLennart RegebroView Answer on Stackoverflow
Solution 2 - PythonDenis OtkidachView Answer on Stackoverflow
Solution 3 - PythonGreg HewgillView Answer on Stackoverflow
Solution 4 - PythonEmma LabbéView Answer on Stackoverflow
Solution 5 - PythonEric LeschinskiView Answer on Stackoverflow
Solution 6 - PythonluoziluojunView Answer on Stackoverflow