检查 x 是否为模块的 Python 方法

问题描述 投票:0回答:2

这适用于内置类型(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 的方式吗?

python syntax
2个回答
0
投票

您可以使用

inspect
模块,或者您可以使用具有适当类型的
isinstance

>>> import inspect
>>> import types
>>> inspect.ismodule(inspect)
True
>>> isinstance(inspect, types.ModuleType)
True

-1
投票

是的,有更好更“pythonic”的方式来做到这一点。您可以使用 Python 的内置

inspect
模块。
inspect
模块提供了几个功能,允许您检查对象的类型,包括模块!

© www.soinside.com 2019 - 2024. All rights reserved.