python--inspect,,inspect是专门


inspect是专门用来收集python对象的信息的,可以获取参数信息,原码,解析堆栈,判断对象类型等等。下面看看一些主要用法

import inspect# 1.判断是不是一个模块import tornadoprint(inspect.ismodule(tornado))  # True# 2.判断是不是一个类Foo = type("Foo", (object, ), {})print(inspect.isclass(Foo))  # True# 3.判断是不是一个方法。说白了就是判断是不是类里面定义的一个函数,class A:    def m(self):        ...print(inspect.ismethod(A().m), type(A().m))  # True <class ‘method‘># 4.判断是不是一个方法描述符。说白了就是首先得是一个类的实例对象,并且这个类里面定义了__get__方法,且没有定义__set__方法class A:    def __get__(self, instance, owner):        ...print(inspect.ismethoddescriptor(A()))# 5.判断是不是一个数据描述符。说白了就是首先得是一个类的实例对象,并且这个类里面定义了__get__方法和__set__方法class A:    def __get__(self, instance, owner):...    def __set__(self, instance, value):...print(inspect.isdatadescriptor(A()))  # True# 6.判断是不是一个函数print(inspect.isfunction(lambda: ...))  # True# 7.判断是不是一个生成器函数def foo(): yield 1print(inspect.isgeneratorfunction(foo))  # True# 同时生成器函数也是一个函数print(inspect.isfunction(foo))  # True# 8.判断是不是一个协程函数,协程函数必须是由async def语法定义的函数,使用types.coroutine或者asyncio.coroutine装饰的函数都不是async def foo():    ...print(inspect.iscoroutinefunction(foo))  # True# 9.判断是不是一个异步生成器函数,异步生成器函数是由async def语法定义,并且函数体内部要包含yield的函数async def foo():    yield 1print(inspect.isasyncgenfunction(foo))  # True# 10.判断是不是一个异步生成器,就是异步生成器函数加上小括号print(inspect.isasyncgen(foo()))  # True# 11.判断是不是一个生成器, 就是生成器函数加上小括号def gen(): yield 1print(inspect.isgenerator(gen()))  # True# 12.判断是不是一个协程,就是协程函数加上小括号async def foo(): ...print(inspect.iscoroutine(foo()))  # True# 13.判断是不是一个可以awaitable,说白了就是await一个迭代器对象async def foo():    await [1, 2, 3].__iter__()print(inspect.isawaitable(foo()))  # True# 14.判断是不是一个栈帧def foo():    # 该函数可以获取栈帧    frame = inspect.currentframe()    return frameprint(inspect.isframe(foo()))  # True# 15.判断是是不是codedef foo(): ...print(inspect.iscode(foo.__code__))  # True# 16.获取成员class A:    def __init__(self):...    def parse(self): ...import pprintpprint.pprint(inspect.getmembers(A))‘‘‘[(‘__class__‘, <class ‘type‘>), (‘__delattr__‘, <slot wrapper ‘__delattr__‘ of ‘object‘ objects>), (‘__dict__‘,  mappingproxy({‘__dict__‘: <attribute ‘__dict__‘ of ‘A‘ objects>,                ‘__doc__‘: None,                ‘__init__‘: <function A.__init__ at 0x000001FEF344CEA0>,                ‘__module__‘: ‘__main__‘,                ‘__weakref__‘: <attribute ‘__weakref__‘ of ‘A‘ objects>,                ‘parse‘: <function A.parse at 0x000001FEF344CF28>})), (‘__dir__‘, <method ‘__dir__‘ of ‘object‘ objects>), (‘__doc__‘, None), (‘__eq__‘, <slot wrapper ‘__eq__‘ of ‘object‘ objects>), (‘__format__‘, <method ‘__format__‘ of ‘object‘ objects>), (‘__ge__‘, <slot wrapper ‘__ge__‘ of ‘object‘ objects>), (‘__getattribute__‘, <slot wrapper ‘__getattribute__‘ of ‘object‘ objects>), (‘__gt__‘, <slot wrapper ‘__gt__‘ of ‘object‘ objects>), (‘__hash__‘, <slot wrapper ‘__hash__‘ of ‘object‘ objects>), (‘__init__‘, <function A.__init__ at 0x000001FEF344CEA0>), (‘__init_subclass__‘,  <built-in method __init_subclass__ of type object at 0x000001FEF2E6F628>), (‘__le__‘, <slot wrapper ‘__le__‘ of ‘object‘ objects>), (‘__lt__‘, <slot wrapper ‘__lt__‘ of ‘object‘ objects>), (‘__module__‘, ‘__main__‘), (‘__ne__‘, <slot wrapper ‘__ne__‘ of ‘object‘ objects>), (‘__new__‘, <built-in method __new__ of type object at 0x00007FFFC0D98EC0>), (‘__reduce__‘, <method ‘__reduce__‘ of ‘object‘ objects>), (‘__reduce_ex__‘, <method ‘__reduce_ex__‘ of ‘object‘ objects>), (‘__repr__‘, <slot wrapper ‘__repr__‘ of ‘object‘ objects>), (‘__setattr__‘, <slot wrapper ‘__setattr__‘ of ‘object‘ objects>), (‘__sizeof__‘, <method ‘__sizeof__‘ of ‘object‘ objects>), (‘__str__‘, <slot wrapper ‘__str__‘ of ‘object‘ objects>), (‘__subclasshook__‘,  <built-in method __subclasshook__ of type object at 0x000001FEF2E6F628>), (‘__weakref__‘, <attribute ‘__weakref__‘ of ‘A‘ objects>), (‘parse‘, <function A.parse at 0x000001FEF344CF28>)]‘‘‘# 17.获取mro,包括自己class A(object): ...print(inspect.getmro(A))  # (<class ‘__main__.A‘>, <class ‘object‘>)# 18.获取docprint(inspect.getdoc(int))‘‘‘int([x]) -> integerint(x, base=10) -> integerConvert a number or string to an integer, or return 0 if no argumentsare given.  If x is a number, return x.__int__().  For floating pointnumbers, this truncates towards zero.If x is not a number or if base is given, then x must be a string,bytes, or bytearray instance representing an integer literal in thegiven base.  The literal can be preceded by ‘+‘ or ‘-‘ and be surroundedby whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.Base 0 means to interpret the base from the string as an integer literal.>>> int(‘0b100‘, base=0)4‘‘‘# 19.查看对象被定义在哪一个文件里面from pandas import DataFrameprint(inspect.getfile(DataFrame))  # C:\python37\lib\site-packages\pandas\core\frame.py# 当然也可以是一个模块import requestsprint(inspect.getfile(requests))  # C:\python37\lib\site-packages\requests\__init__.py# 20.返回一个给定对象的模块名,不过存在不存在,感觉没卵用print(inspect.getmodulename(r"C:\python37\lib\site-packages\peeaaawee.py"))  # peeaaawee# 21.和getfile类似print(inspect.getabsfile(DataFrame))  # c:\python37\lib\site-packages\pandas\core\frame.py# 22.获取参数信息,但需要传入字节码def foo(a, b=1): ...print(inspect.getargs(foo.__code__))  # Arguments(args=[‘a‘, ‘b‘], varargs=None, varkw=None)print(inspect.getargs(foo.__code__).args)  # [‘a‘, ‘b‘]# 23.获取参数信息吗, 传入函数即可def foo(a, b=1): ...print(inspect.getfullargspec(foo))  # FullArgSpec(args=[‘a‘, ‘b‘], varargs=None, varkw=None, defaults=(1,), kwonlyargs=[], kwonlydefaults=None, annotations={})print(foo.__defaults__)  # (1,)

  

import inspectdef bar():    name = "Mashiro"    age = 16    return foo()def foo():    name = "Satori"    age = 18    return inspect.currentframe()# frame叫做栈帧,表示当前函数调用栈的某一帧,是一个上下文。正所谓在python中一切皆对象,这个栈帧也是一个对象。# 函数执行要在相应的栈帧中执行# 栈帧有一下几大特性,# f_back:调用者的上一级栈帧# f_code:字节码# f_lineno:栈帧所在的哪一行# frame是定义在foo函数里面,所以currentframe拿到的是foo的栈帧# 但是又是通过bar来调用的,所以foo的上一级栈帧就是bar的栈帧f = bar()print(f.f_back)  # <frame at 0x000001E1FF4CF458, file ‘D:/乱七八糟的/龙卷风/3.py‘, line 5, code bar>print(f.f_code)  # <code object foo at 0x000001E1FFEE3F60, file "D:/乱七八糟的/龙卷风/3.py", line 8>print(f.f_lineno)  # 13# 这个f_code里面也有很多的属性# co_name:获取栈帧所对应的函数名print(f.f_code.co_name)  # foo# co_filename:获取相应的文件名print(f.f_code.co_filename)  # D:/乱七八糟的/龙卷风/3.pyprint(f.f_back.f_code.co_name)  # barprint(f.f_back.f_code.co_filename)  # D:/乱七八糟的/龙卷风/3.py# 查看当前的局部变量,可以看到由于栈帧还在,所以局部变量依旧存储在堆上print(f.f_locals)  # {‘name‘: ‘Satori‘, ‘age‘: 18}# 同理它的上一级栈帧也是print(f.f_back.f_locals)  # {‘name‘: ‘Mashiro‘, ‘age‘: 16}# 如果是生成器的话,就不需要了def gen():    yield 1    name = ("xxx", )    yield 2    age = 16    yield 3    gender = "f"    yield 4    returng = gen()# 生成器有一个gi_frame属性,可以直接获取print(g.gi_frame.f_locals)  # {}print(next(g))  # 1print(g.gi_frame.f_locals)  # {}print(next(g))  # 2print(g.gi_frame.f_locals)  # {‘name‘: ‘xxx‘}print(next(g))  # 3print(g.gi_frame.f_locals)  # {‘name‘: ‘xxx‘, ‘age‘: 16}print(next(g))  # 4print(g.gi_frame.f_locals)  # {‘name‘: ‘xxx‘, ‘age‘: 16, ‘gender‘: ‘f‘}try:    next(g)except StopIteration as e:    print(e.value)  # result

  

  

python--inspect

评论关闭