Python - inspect 模块的简单使用

Python中的inspect模块解析

Python的inspect模块是一个强大的内省工具,允许开发者检查(inspect)活动对象和源代码。它提供了一系列函数,用于获取信息关于正在运行的程序和调用堆栈,非常适合进行调试和动态分析。本文将通过介绍inspect模块的关键功能,并结合实际案例代码,来探索其在日常开发中的应用。

常用方法

1. 获取当前执行的函数或方法名、文件路径【并不是调用方】

在日志记录或调试时,知道当前执行的函数名是非常有用的

python 复制代码
import inspect

def who_am_i():
    # 输出当前文件绝对路径
    print(inspect.currentframe().f_code.co_filename)
    return inspect.currentframe().f_code.co_name

print(who_am_i())  # 输出: who_am_i

个人认为比较有用的就是 co_filename、co_name

2. 获取调用者信息

获取当前函数或方法的调用者信息

python 复制代码
import inspect

def caller_info():
    frame = inspect.currentframe().f_back
    print(f调用者 {frame.f_code.co_filename} 调用行号 d{frame.f_lineno}")

def test():
    caller_info()  # 调用以获取调用者信息

test()

这个例子显示了如何获取调用当前函数的代码位置,非常有助于调试复杂的调用链

3. 查看函数参数

inspect模块可以用来检查函数或方法的参数,这对于动态分析和生成文档非常有用

python 复制代码
import inspect

def sample_function(name, age=25):
    pass

sig = inspect.signature(sample_function)
print(sig)  # 输出: (name, age=25)

4. 获取源代码

inspect还可以用来获取函数、类或模块的源代码

python 复制代码
import inspect

def my_function():
    """A simple function."""
    pass

print(inspect.getsource(my_function))

5. 检查类和实例

inspect模块提供了多种方式来检查类和实例,比如获取类的所有方法、属性等

python 复制代码
class MyClass:
    def method_one(self):
        pass
    
    def method_two(self):
        pass

# 获取类的所有成员方法
methods = inspect.getmembers(MyClass, predicate=inspect.isfunction)
print(methods)  # 输出 MyClass 中定义的方法

实际案例:自动化场景下的应用

一个常见的使用场景是动态地调用函数或方法,并基于它们的签名自动生成文档。

python 复制代码
def test():
    # 获取调用方
    frame = inspect.currentframe().f_back
    # 获取调用方文件绝对路径
    caller_file = inspect.getfile(frame)
    # 这种方式也可以
    caller_file = frame.f_code.co_filename

    ...
    
    params = [
        caller_file,
        "--env-data",
        env_data.json(),
        f"--count={count}",
        "-m",
        mark,
    ]

一个基于 Pytest 自动化测试项目

  1. 每个 py 模块都会调用这个方法来执行 Pytest 命令来跑测试用例
  2. 那怎么才能准确知道要跑哪个文件呢?
  3. 通过第一、二行代码即可

更便捷的方式

相关推荐
小九九的爸爸8 小时前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学9 小时前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田1 天前
Pydantic校验配置文件
python
hboot1 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi1 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi2 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽2 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187912 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L2 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅2 天前
海天线算法的前世今生
python·计算机视觉