Python Inspect 模块

2024年8月29日 | 阅读 7 分钟

在本教程中,我们将学习 Python 的 inspect 模块及其功能。该模块用于检查我们代码中的对象。众所周知,Python 是一种面向对象的语言,我们的代码围绕这些对象运行,因此 inspect 模块在识别特定模块或对象时非常有用。它在检查特定函数调用或回溯时特别有用,从而有助于更顺畅的调试过程。

inspect 模块提供了一系列方法,这些方法可以分为两类:用于确认令牌类型的方法,以及用于获取令牌源代码的方法。

验证令牌类型的方法

以下是验证令牌类型的方法 -

  • isclass(): 如果对象是类,此方法将返回 True;否则返回 False。当与 getmembers() 函数结合使用时,它会显示类及其类型。此方法用于检查活动的类。

让我们理解以下示例 -

示例 -

输出

Is MyClass a class - True
Is my_function a class -  False

在此示例中,isclass() 方法用于检查 MyClass 和 my_function 对象是否为类。对于 MyClass(因为它是一个类),结果将是 True;对于 my_function(因为它不是一个类),结果将是 False。

  • ismodule(): 如果提供的参数是已导入的模块,此函数将返回 True。

示例 -

输出

Is math a module - True
Is 'hello' a module - False
  • isfunction() - 如果提供的参数是内置函数名,此方法将返回 True。

示例 -

输出

Is my_function a function - True
Is print a function - True
  • ismethod() - 此函数用于确定提供的参数是否对应于方法名。

示例 -

输出

Is my_method a method -  True
Is my_function a method -  False

检索令牌源代码的方法

getclasstree(): `getclasstree()` 函数可用于获取和检查类层次结构。它提供一个元组,其中包含类本身及其父类。当与返回父类的 getmro() 函数配对使用时,它有助于理解类层次结构。

示例 -

输出

[(<class '__main__.D'>, (<class '__main__.C'>,)), (<class '__main__.B'>, (<class '__main__.A'>,))]

解释 -

在上面的代码中 -

  1. 我们定义了四个类:A、B、C 和 D。每个类都是其前一个类的子类,遵循继承层次结构。
  2. 使用 `inspect.getclasstree()` 函数来检索两个指定类 D 和 B 的类层次结构。`unique=True` 参数确保类层次结构中不会重复出现重复的类。
  3. `inspect.getclasstree()` 函数调用的输出显示为元组列表,其中每个元组包含一个类及其父类。元组的结构代表了继承链。在输出中,可以看出类 D 派生自类 C,类 C 又派生自类 B,类 B 派生自类 A。
  • getmembers(): 此函数提供在作为参数传递给该函数的模块中找到的成员函数列表。

示例

输出

Members of my_function: [('__annotations__', {}), ('__call__', <method-wrapper '__call__' of function object at 0x7f3d91d76ca0>), ('__class__', <class 'function'>), ... ]
Members of MyClass: [('__class__', <class 'type'>), ('__delattr__', <slot wrapper '__delattr__' of 'object' objects>), ('__dict__', <attribute '__dict__' of 'MyClass' objects>), ... ]

在此代码中,`getmembers()` 函数用于检索 `my_function` 函数和 `MyClass` 类的成员。输出显示了这些实体各自的成员列表。

我们也可以获取模块的成员。

示例 - 2

输出

[('CLOCK_BOOTTIME', 7), ('CLOCK_MONOTONIC', 1), ('CLOCK_MONOTONIC_RAW', 4), ('CLOCK_PROCESS_CPUTIME_ID', 2), ('CLOCK_REALTIME', 0), ('CLOCK_TAI', 11), ('CLOCK_THREAD_CPUTIME_ID', 3), ('_STRUCT_TM_ITEMS', 11), ('__doc__', 'This module provides various functions to manipulate time values.\n\nThere are two standard representations of time.  One is the number\nof seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer\nor a floating point number (to represent fractions of seconds).\nThe Epoch is system-defined; on Unix, it is generally January 1st, 1970.\nThe actual value can be retrieved by calling gmtime(0).\n\nThe other representation is a tuple of 9 integers giving local time.\nThe tuple items are:\n  year (including century, e.g. 1998)\n  month (1-12)\n  day (1-31)\n  hours (0-23)\n  minutes (0-59)\n  seconds (0-59)\n  weekday (0-6, Monday is 0)\n  Julian day (day in the year, 1-366)\n  DST (Daylight Savings Time) flag (-1, 0 or 1)\nIf the DST flag is 0, the time is given in the regular time zone;\nif it is 1, the time is given in the DST time zone;\nif it is -1, mktime() should guess based on the date and time.\n'), ('__loader__', <class '_frozen_importlib.BuiltinImporter'>), ('__name__', 'time'), ('__package__', ''), ('__spec__', ModuleSpec(name='time', loader=<class '_frozen_importlib.BuiltinImporter'>, origin='built-in')), ('altzone', 0), ('asctime', <built-in function asctime>), ('clock_getres', <built-in function clock_getres>), ('clock_gettime', <built-in function clock_gettime>), ('clock_gettime_ns', <built-in function clock_gettime_ns>), ('clock_settime', <built-in function clock_settime>), ('clock_settime_ns', <built-in function clock_settime_ns>), ('ctime', <built-in function ctime>), ('daylight', 0), ('get_clock_info', <built-in function get_clock_info>), ('gmtime', <built-in function gmtime>), ('localtime', <built-in function localtime>), ('mktime', <built-in function mktime>), ('monotonic', <built-in function monotonic>), ('monotonic_ns', <built-in function monotonic_ns>), ('perf_counter', <built-in function perf_counter>), ('perf_counter_ns', <built-in function perf_counter_ns>), ('process_time', <built-in function process_time>), ('process_time_ns', <built-in function process_time_ns>), ('pthread_getcpuclockid', <built-in function pthread_getcpuclockid>), ('sleep', <built-in function sleep>), ('strftime', <built-in function strftime>), ('strptime', <built-in function strptime>), ('struct_time', <class 'time.struct_time'>), ('thread_time', <built-in function thread_time>), ('thread_time_ns', <built-in function thread_time_ns>), ('time', <built-in function time>), ('time_ns', <built-in function time_ns>), ('timezone', 0), ('tzname', ('UTC', 'UTC')), ('tzset', <built-in function tzset>)]
  • signature(): `signature()` 函数有助于用户理解需要提供给函数的属性。

示例

输出

Function signature: (x, y=0, *args, **kwargs)

在此示例中,`signature()` 函数用于确定 my_function() 函数的签名。输出显示了函数的签名,包括其参数和特殊参数类型。

stack(): `stack()` 函数有助于检查解释器堆栈,显示函数被调用的顺序。

示例 -

输出

Function call stack: [FrameInfo(frame=<frame at 0x7f785c0ad8e0, file 'example.py', line 6, code function function_two>, filename='example.py', lineno=6, function='function_two', code_context=['    function_two()\n'], index=0), ...]

在此示例中,`stack()` 函数用于检索和显示有关调用堆栈的信息。输出提供了堆栈中帧的详细信息,包括文件位置、行号和函数名。

示例 - 2

输出

Function call stack: [FrameInfo(frame=<frame at 0x7f6d59cc0b80, file '<string>', line 13, code main>, filename='<string>', lineno=12, function='main', code_context=None, index=None, positions=Positions(lineno=12, end_lineno=12, col_offset=19, end_col_offset=34)), FrameInfo(frame=<frame at 0x7f6d59a22ca0, file '<string>', line 18, code <module>>, filename='<string>', lineno=18, function='<module>', code_context=None, index=None, positions=Positions(lineno=18, end_lineno=18, col_offset=0, end_col_offset=6))]
Fibonacci result: 5
  • getsource() - getsource() 函数检索指定模块、类、方法或函数的源代码。

示例 -

输出

Source code of MyClass:
class MyClass:
    def __init__(self, value):
        self.value = value

    def get_value(self):
        return self.value

在此示例中,`getsource()` 函数用于检索和显示 `MyClass` 类的源代码。输出显示了类的源代码,包括其方法和属性。

  • getmodule() - `getmodule()` 函数提供与作为参数传递的特定对象关联的模块名。

示例 -

输出

Module name of my_function: __main__

在此示例中,`getmodule()` 函数用于检索 `my_function` 函数的模块名。输出显示了定义该函数的模块的名称。

  • getdoc(): `getdoc()` 函数提供作为参数传递的指定对象的文档,以字符串形式显示。

示例

输出

Documentation of my_function:
This is a sample function.

结论

总之,`inspect` 模块对于 Python 程序员来说是一个非常有用的库。它帮助他们仔细查看代码的不同部分,如类、函数等。这使得开发人员能够理解内部发生的情况并修复任何问题。无论他们是想查看事物之间的连接方式、查看实际代码,还是理解函数的工作原理,`inspect` 模块都能满足他们的需求。