检查参数是否为Python模块?

2024-04-29 16:20:20 发布

您现在位置:Python中文网/ 问答频道 /正文

如何(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 290, in __run
    r = eval(command, self.namespace, self.namespace)
  File "<string>", line 1, in <module>
NameError: name 'module' is not defined

我可以做到:

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

但我该拿它和什么比较呢?:(一)

我制作了一个简单的模块,可以快速找到模块中的方法,并为它们获取帮助文本。我为我的方法提供一个模块变量和一个字符串:

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])

当然,即使module='abc':那么dir('abc')会给我string对象的方法列表,但我不需要它。


Tags: 模块方法inselfstringisoslib
3条回答

这看起来有点老套,但是:

>>> import sys
>>> import os
>>> type(os) is type(sys)
True
>>> import inspect, os
>>> inspect.ismodule(os)
True
from types import ModuleType

isinstance(obj, ModuleType)

相关问题 更多 >