检查参数是否为Python模块?
如何(pythonically)检查参数是否是Python模块?没有模块或包这样的类型检查参数是否为Python模块?,python,types,Python,Types,如何(pythonically)检查参数是否是Python模块?没有模块或包这样的类型 >>> 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
>>> 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
当然,即使module='abc':那么dir('abc')会给我string对象的方法列表,但我不需要它。这似乎有点老套,但是:
>>> import sys
>>> import os
>>> type(os) is type(sys)
True
一系列问题和答案:
将模块展平为字符串并检查它是否以
开头两种方式,您无法导入任何模块:
type(os)是类型(\uuuu内置的)
str(类型(os)).find('module')>-1
您知道help()方法和pydoc以及类似的工作,对吧?pydoc有点不同。我需要一个简单的方法来找到一个方法,而不知道它的确切名称。例如,在os.path中有“size”的东西。您不能键入一个模块吗?你需要它做什么?只要尝试一下,如果失败就捕获异常。好吧,docs and help是一种内省,所以在这种情况下似乎没问题。呵呵,在标准库中,moduletypes
,发现了这样一个问题:ModuleType=type(sys)
:)为什么这是公认的答案?包也是的一个实例ModuleType@Wang我不相信Python中的“包”和“模块”之间有任何区别。它们都是模块。
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])
>>> import sys
>>> import os
>>> type(os) is type(sys)
True
from types import ModuleType
isinstance(obj, ModuleType)
>>> import inspect, os
>>> inspect.ismodule(os)
True
>>> from types import ModuleType
>>> import os
>>> type(os) is ModuleType
True
import matplotlib
foobarbaz = "some string"
print(str(matplotlib).startswith("<module ")) #prints True
print(str(foobarbaz).startswith("<module ")) #prints False