python inspect模块
简介
在查看python高阶相关知识时发现了一个inspect模块,中文含义就是检查,它可以获取类中相关对象的信息,例如获取函数的参数以及方法的源码等,官网所说的功能便是类型检查、获取源代码、检查类与函数、检查解释器的调用堆栈。
类型和成员
假设存在如下类
class Test:
instance = []
def __init__(self, name) -> None:
self.name = name
def run(self):
print(f"run:{self.name}")
@staticmethod
def static_method(self):
print("static_method")
inspect.getmembers(object[, predicate])
获取对象中的所有成员(包含方法、函数、属性),以列表中嵌套对应元组返回,上述类的结果如下:
[('__class__', <class '__main__.Test'>), ('__delattr__', <method-wrapper '__delattr__' of Test object at 0x00000211ACE05EA0>), ('__dict__', {'name': 'tom'}), ('__dir__', <built-in method __dir__ of Test object at 0x00000211ACE05EA0>), ('__doc__', None), ('__eq__', <method-wrapper '__eq__' of Test object at 0x00000211ACE05EA0>), ('__format__', <built-in method __format__ of Test object at 0x00000211ACE05EA0>), ('__ge__', <method-wrapper '__ge__' of Test object at 0x00000211ACE05EA0>), ('__getattribute__', <method-wrapper '__getattribute__' of Test object at 0x00000211ACE05EA0>), ('__gt__', <method-wrapper '__gt__' of
Test object at 0x00000211ACE05EA0>), ('__hash__', <method-wrapper '__hash__' of Test object at 0x00000211ACE05EA0>), ('__init__', <bound method Test.__init__ of <__main__.Test object at 0x00000211ACE05EA0>>), ('__init_subclass__', <built-in method __init_subclass__ of type object at 0x00000211ACF031A0>), ('__le__', <method-wrapper '__le__' of Test object at 0x00000211ACE05EA0>), ('__lt__', <method-wrapper '__lt__' of Test object at 0x00000211ACE05EA0>), ('__module__', '__main__'), ('__ne__', <method-wrapper '__ne__' of Test object at 0x00000211ACE05EA0>), ('__new__', <built-in method __new__ of type object at 0x00007FF9E43CB780>), ('__reduce__', <built-in method __reduce__ of Test object at 0x00000211ACE05EA0>), ('__reduce_ex__', <built-in method __reduce_ex__ of Test object at 0x00000211ACE05EA0>), ('__repr__', <method-wrapper '__repr__' of Test object at 0x00000211ACE05EA0>), ('__setattr__', <method-wrapper '__setattr__' of Test object at 0x00000211ACE05EA0>), ('__sizeof__', <built-in method __sizeof__ of Test object at 0x00000211ACE05EA0>), ('__str__', <method-wrapper '__str__' of Test object at 0x00000211ACE05EA0>), ('__subclasshook__', <built-in method __subclasshook__ of type object at 0x00000211ACF031A0>), ('__weakref__', None), ('instance', []), ('name', 'tom'), ('run', <bound method Test.run of <__main__.Test object at 0x00000211ACE05EA0>>), ('static_method', <function Test.static_method at 0x00000211AD076200>)]
与这个方法类似的有一个名为dir的函数或者__dir__
,它也可以获取对象中的属性,区别在于它只会返回对象中包含哪些成员,不会显示成员的实际对应内容。
inspect.getmodulename(path)
返回path文件名包含的模块名称,目前发现只会对.py
、.pyc
文件做处理,类似于就是获取path的文件名称。示例如下
print(inspect.getmodulename(r"C:\Users\ts\Desktop\2022.7\2022.9.13\test2.py"))
test2
判断对象是否为某一类型
例如判断是否是函数、方法、类、模块、特殊对象等,详细可见官网的相关信息
获取源代码
import inspect
class Test(object):
"""Test"""
# run
def __init__(self) -> None:
pass
# run
def run(self):
"""run"""
print("run")
t = Test()
# 获取对象或者模块的注释
print(inspect.getdoc(t))
print(inspect.getcomments(t))
# 获取对象所在的文件
print(inspect.getfile(Test))
# 获取对象所在的模块
print(inspect.getmodule(Test))
# 获取对象所在的文件
print(inspect.getsourcefile(Test))
# 获取对象的所在的源代码,以列表形式呈现
print(inspect.getsourcelines(Test))
# 获取对象所在的源代码,以字符串形式呈现
print(inspect.getsource(Test))
signature对象
是用于自省的对象,可以获得函数的参数及返回值,也可以进行函数参数的约束。
import inspect
def run(x, y, z) -> str:
"""run"""
print("run")
return "test"
t = inspect.signature(run)
# 获取参数及返回值
print(str(t))
# 获取参数,以有序字典形式返回,会包含参数的类型
print(t.parameters)
# 设置构造一个位置和关键字实参到形参的映射
print(t.bind_partial(int, int, int).arguments)
print(t.bind_partial(1, 2, 3).arguments)
# 获取返回值
print(t.return_annotation)