Python inspect 模块核心功能解析
inspect 是 Python 标准库中用于 运行时自省(introspection) 的模块,主要用于分析代码结构、检查对象属性、提取函数签名等场景。
核心功能概览
功能类别 典型应用场景 关键函数/方法示例
类型检查 判断对象类型(类、函数、模块等) ismodule(), isclass(), isfunction()
源代码提取 获取函数/类的源代码或文档字符串 getsource(), getdoc(), getfile()
参数与签名解析 分析函数的参数列表及默认值 signature(), getfullargspec()
调用堆栈分析 调试时获取调用栈信息 stack(), currentframe(), getouterframes()
对象成员遍历 动态获取对象的属性和方法 getmembers(), getmodule()
功能详解与代码示例
- 类型检查
通过 isXXX() 系列函数快速判断对象类型:
import inspect
def demo_func(): pass
class DemoClass: pass
print(inspect.isfunction(demo_func)) # True :ml-citation{ref=“3” data=“citationList”}
print(inspect.isclass(DemoClass)) # True :ml-citation{ref=“3” data=“citationList”}
print(inspect.ismodule(inspect)) # True :ml-citation{ref=“4,6” data=“citationList”}
- 获取源代码
提取函数或类的源代码:
# 获取函数源码
print(inspect.getsource(demo_func)) # 输出函数定义代码 :ml-citation{ref=“3,4” data=“citationList”}
获取模块文件路径
print(inspect.getfile(inspect)) # 输出 inspect 模块的物理路径 :ml-citation{ref=“1,6” data=“citationList”}
- 参数签名解析
分析函数的参数结构:
def func(a: int, b=10, *args, c: str, **kwargs) -> float:
pass
sig = inspect.signature(func)
print(sig.parameters)
# 输出有序字典,包含参数名、类型、默认值等信息 :ml-citation{ref=“3,4” data=“citationList”}
- 调用堆栈分析
调试时获取调用栈信息:
def debug_trace():
frame = inspect.currentframe()
caller_info = inspect.getframeinfo(frame.f_back)
print(f"调用文件: {caller_info.filename}, 行号: {caller_info.lineno}") :ml-citation{ref=“1,4” data=“citationList”}
debug_trace()
- 对象成员遍历
动态获取对象的属性和方法:
class MyClass:
attr = 100
def method(self): pass
members = inspect.getmembers(MyClass)
# 返回包含 (属性名, 属性值) 的列表 :ml-citation{ref=“1,6” data=“citationList”}
典型应用场景
动态文档生成:提取函数签名和参数描述生成 API 文档。
调试工具开发:捕获调用栈信息定位错误。
反射编程:根据字符串动态调用函数或实例化类。
代码分析工具:检查模块依赖关系或代码结构。
注意事项
性能影响:频繁使用 inspect 可能降低程序性能,需谨慎用于高频调用场景。
内置对象限制:部分内置函数或 C 扩展模块可能无法获取完整信息。
版本兼容性:部分函数行为在不同 Python 版本中存在差异(如 signature() 对装饰器的处理)。
通过灵活运用 inspect 模块,开发者可以实现对 Python 代码的深度自省和动态操作,显著提升框架开发、调试和自动化工具的构建效率。