Python导入模块时如何判断其中包含的是函数、类还是二者都有?
Python判断导入模块的成员类型方案
你可以通过Python标准库自带的inspect模块实现需求,不需要打开模块源码,也不需要依赖第三方工具,实现逻辑如下:
核心实现代码
import inspect # 替换为你要检查的目标模块,比如import requests import 目标模块 def check_module_content(module): # 遍历模块所有成员,排除下划线开头的私有/内置成员 all_members = inspect.getmembers(module) public_members = [item for item in all_members if not item[0].startswith('_')] has_function = False has_class = False for name, obj in public_members: # 排除模块内导入的外部成员,只统计当前模块自身定义的内容,不需要可删掉下一行 if getattr(obj, '__module__', None) != module.__name__: continue # 判断是否为函数(含C实现的内置函数) if inspect.isfunction(obj) or inspect.isbuiltin(obj): has_function = True # 判断是否为类 if inspect.isclass(obj): has_class = True if has_function and has_class: return "模块同时包含公开函数和公开类" elif has_function: return "模块仅包含公开函数" elif has_class: return "模块仅包含公开类" else: return "模块无公开的函数/类成员" # 调用示例 print(check_module_content(目标模块))
可选调整说明
- 不需要统计C实现的内置函数的话,删掉
or inspect.isbuiltin(obj)即可 - 需要识别更细分的成员类型时,可扩展
inspect的对应方法:比如用inspect.iscoroutinefunction判断异步函数、inspect.isabstract判断抽象类
内容的提问来源于stack exchange,提问作者user17273882
相关产品推荐
相关产品推荐

