How can I (pythonically) check if a parameter is a Python module? There\'s no type like module or package.
>>> os
A mix of @Greg Hewgill and @Lennart Regebro answers:
>>> from types import ModuleType
>>> import os
>>> type(os) is ModuleType
True
from types import ModuleType
isinstance(obj, ModuleType)
>>> import inspect, os
>>> inspect.ismodule(os)
True
This seems a bit hacky, but:
>>> import sys
>>> import os
>>> type(os) is type(sys)
True
Two ways,you could not import any modules:
type(os) is type(__builtins__)
str(type(os)).find('module')>-1
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.