这适用于内置类型(str、list、int 等)和正确导入的类,但不适用于模块:
type(x) is module #NameError: name 'module' is not defined.
有解决方法:
str(type(x)) == "<class 'module'>"
type(x) is type(os) # Or any imported module object.
但是还有更 pythonic 的方式吗?
您可以使用
inspect
模块,或者您可以使用具有适当类型的isinstance
。
>>> import inspect
>>> import types
>>> inspect.ismodule(inspect)
True
>>> isinstance(inspect, types.ModuleType)
True
是的,有更好更“pythonic”的方式来做到这一点。您可以使用 Python 的内置
inspect
模块。 inspect
模块提供了几个功能,允许您检查对象的类型,包括模块!