Python 的 inspect 模块提供了一组函数,用于检查对象的类型、属性、方法以及源代码等信息。它在调试、开发和反射操作中非常有用。以下是 inspect 模块的主要功能和用法:


常用功能

  1. 检查对象的类型和属性

    • 查看函数、类或模块的结构。
    • 判断对象是否为函数、类、方法等特定类型。
  2. 获取对象的源码

    • 提取函数、类或方法的定义代码。
  3. 获取函数签名

    • 获取函数的参数信息,包括默认值和类型注解。
  4. 分析堆栈信息

    • 在调试时,查看当前调用堆栈和上下文信息。

主要函数及示例

1. 检查对象的类型

使用 isfunctionismethod 等函数判断对象的类型。

import inspect

def example_function():
    pass

class ExampleClass:
    def method(self):
        pass

print(inspect.isfunction(example_function))  # True
print(inspect.isclass(ExampleClass))         # True
print(inspect.ismethod(ExampleClass.method)) # False (未绑定的方法是函数)

2. 获取函数签名

使用 signature 获取函数的参数信息。

import inspect

def sample_function(a, b: int, c=10, *args, **kwargs) -> str:
    return "example"

sig = inspect.signature(sample_function)
print(sig)  # (a, b: int, c=10, *args, **kwargs) -> str

for param_name, param in sig.parameters.items():
    print(f"Name: {param_name}, Default: {param.default}, Annotation: {param.annotation}")
# 输出:
# Name: a, Default: <class 'inspect._empty'>, Annotation: <class 'inspect._empty'>
# Name: b, Default: <class 'inspect._empty'>, Annotation: <class 'int'>
# Name: c, Default: 10, Annotation: <class 'inspect._empty'>

什么是函数签名?
函数签名 是函数定义中的核心部分,它描述了函数的 参数列表 和 返回值类型(如果有)。简单来说,函数签名包括函数的名称、参数的名称和类型、默认值以及返回值类型。
例如:def multiply(a: int, b: int = 1) -> int: return a * b 的函数签名可以写成multiply(a: int, b: int = 1) -> int


3. 获取对象的源码

使用 getsource 获取函数、类或模块的定义源码。

import inspect

def example_function():
    print("Hello, world!")

source = inspect.getsource(example_function)
print(source)
# 输出:
# def example_function():
#     print("Hello, world!")

4. 获取调用堆栈

使用 stacktrace 获取当前调用堆栈信息。

import inspect

def first_function():
    second_function()

def second_function():
    stack = inspect.stack()
    for frame in stack:
        print(f"Function: {frame.function}, Line: {frame.lineno}")

first_function()
# 输出:
# Function: second_function, Line: <调用行号>
# Function: first_function, Line: <调用行号>
# Function: <module>, Line: <主模块调用行号>

5. 获取类或模块的成员

使用 getmembers 获取类或模块的属性和方法。

import inspect

class ExampleClass:
    def method(self):
        pass

members = inspect.getmembers(ExampleClass)
for name, member in members:
    print(name, member)
# 输出: 类的所有属性和方法,包括 `__init__`, `method`, 等。

6. 检查函数的闭包

使用 getclosurevars 查看函数闭包中的变量。

import inspect

def outer_function(x):
    def inner_function(y):
        return x + y
    return inner_function

closure_function = outer_function(10)
closure_vars = inspect.getclosurevars(closure_function)
print(closure_vars.nonlocals)  # {'x': 10}

常见场景

  1. 动态分析代码结构:分析第三方库或模块的定义和实现。
  2. 开发调试工具:用于调试时显示调用堆栈或变量状态。
  3. 反射操作:动态获取和调用对象的方法。
  4. 文档生成:提取函数签名和注释,生成 API 文档。

inspect 是一个功能强大的工具,在需要动态了解代码或进行反射操作时非常实用。

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐