Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a parameter is a Python module?

Tags:

python

types

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.

like image 764
culebrón Avatar asked Oct 10 '09 09:10

culebrón


People also ask

Is Python a module?

A module is a Python object with arbitrarily named attributes that you can bind and reference. Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code.

How do you check if a variable is a function Python?

So to be specific you will have to use isinstance(f, (types. FunctionType, types. BuiltinFunctionType)). And of course if you strictly want just functions, not callables nor methods.

How do I see what methods are in a Python module?

You can use dir(module) to see all available methods/attributes.

What is __ name __ Python?

The __name__ variable (two underscores before and after) is a special Python variable. It gets its value depending on how we execute the containing script. Sometimes you write a script with functions that might be useful in other scripts as well. In Python, you can import that script as a module in another script.


2 Answers

from types import ModuleType  isinstance(obj, ModuleType) 
like image 150
Lennart Regebro Avatar answered Sep 27 '22 21:09

Lennart Regebro


>>> import inspect, os >>> inspect.ismodule(os) True 
like image 30
Denis Otkidach Avatar answered Sep 27 '22 21:09

Denis Otkidach