当前位置:首页 > Python > 正文

Python inspect模块完全指南:从基础到高级应用 | Python开发教程

Python inspect模块完全指南

深入探索Python反射与自省的核心工具

什么是inspect模块?

Python的inspect模块是标准库中用于自省(introspection)的核心工具,它提供了多种函数来检查活动对象(如模块、类、方法、函数等)的信息,帮助开发者实现元编程和反射操作。

主要功能包括:

  • 获取对象的类型信息
  • 检索源代码
  • 检查类层次结构
  • 提取函数签名
  • 获取对象文档字符串
  • 检查调用栈
  • 查看模块成员

核心功能解析

1. 检查对象类型

使用inspect模块可以精确判断对象的类型:

import inspect

def sample_function():
    pass

class SampleClass:
    def method(self):
        pass

print(inspect.isfunction(sample_function))  # True
print(inspect.ismethod(SampleClass().method))  # True
print(inspect.isclass(SampleClass))  # True
print(inspect.ismodule(inspect))  # True

2. 获取源代码

提取对象定义的源代码:

import inspect

def add(a, b=5):
    """Add two numbers"""
    return a + b

# 获取函数源代码
print(inspect.getsource(add))

# 获取注释
print(inspect.getcomments(add))

# 获取文档字符串
print(inspect.getdoc(add))

3. 函数签名检查

解析函数参数信息:

import inspect

def calculate(a, b, operator='+', *args, **kwargs):
    pass

sig = inspect.signature(calculate)
print("Parameters:", list(sig.parameters))

param = sig.parameters['b']
print(f"Name: {param.name}")
print(f"Default: {param.default}")
print(f"Kind: {param.kind}")

4. 类与继承检查

分析类结构和继承关系:

import inspect

class Base:
    pass

class Derived(Base):
    pass

# 获取类的方法解析顺序
print(inspect.getmro(Derived))

# 检查类成员
print(inspect.getmembers(Derived, predicate=inspect.isfunction))

实际应用场景

自动生成文档

通过提取函数签名和文档字符串,自动生成API文档。

调试工具开发

检查调用栈和当前帧信息,创建强大的调试工具。

动态调用分析

运行时检查对象结构,实现动态调用和插件系统。

高级技巧:创建对象浏览器

以下示例展示如何使用inspect模块创建一个简单的对象浏览器:

import inspect

def object_browser(obj, depth=2, indent=0):
    """递归浏览对象成员"""
    prefix = ' ' * indent
    
    # 获取对象类型
    if inspect.ismodule(obj):
        print(f"{prefix}模块: {obj.__name__}")
    elif inspect.isclass(obj):
        print(f"{prefix}类: {obj.__name__}")
    elif inspect.isfunction(obj) or inspect.ismethod(obj):
        print(f"{prefix}函数: {obj.__name__}")
    else:
        print(f"{prefix}对象: {type(obj).__name__}")
    
    # 递归深度控制
    if depth <= 0:
        return
    
    # 获取成员(排除特殊方法)
    members = inspect.getmembers(obj, 
        predicate=lambda x: not inspect.isbuiltin(x) 
                   and not x.__name__.startswith('__'))
    
    for name, member in members:
        print(f"{prefix}  ├─ {name}: {type(member).__name__}")
        
        # 递归检查模块、类和函数
        if inspect.ismodule(member) or inspect.isclass(member):
            object_browser(member, depth-1, indent+4)

# 使用示例
import math
object_browser(math, depth=1)

注意事项

  • 避免在生产环境中过度使用inspect,可能影响性能
  • 注意递归深度限制,防止无限循环
  • 某些对象(如内置函数)可能无法获取源代码
  • 检查用户输入对象时要谨慎,防止安全风险

掌握inspect模块,提升你的Python元编程能力

通过本教程,你已经学会了inspect模块的核心用法,现在可以开始在你的项目中应用这些技术了!

Python进阶开发

发表评论