tags:

views:

175

answers:

3

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.

A: 

This seems a bit hacky, but:

>>> import sys
>>> import os
>>> type(os) is type(sys)
True
Greg Hewgill
Yes, it's not quite clean.
Andrey Vlasovskikh
+5  A: 
from types import ModuleType

isinstance(obj, ModuleType)
Lennart Regebro
Please use indent to mark it as code. +1 though, didn't know this.
Maiku Mori
Hah! Who gave -1 on this?!? People are funny.
Lennart Regebro
You've just repeated what I said earlier, and my answer was more complete suggesting why this code is pythonic. Actually I should't vote against your answer, sorry.
Andrey Vlasovskikh
Yeah, except that you were two minutes after me. :)
Lennart Regebro
As I cannot rollback my vote, +1 to your comment :)
Andrey Vlasovskikh
+6  A: 
>>> import inspect, os
>>> inspect.ismodule(os)
True
Denis Otkidach