The inspect module of python reflection

Get into the habit of writing together! This is the sixth day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

The inspect module provides a series of functions for introspection operations. It will be described below.

The classes and functions involved are as follows:

def test_func(name, age, sex="男", *ids, **info):
    """
    返回个人信息
    :param name: 姓名
    :param age: 年龄
    :param sex: 性别
    :return: 个人信息
    """
    return name + "," + age + "," + sex
​
​
class Person(object):
    """
    这是一个测试类
    """
​
    def __init__(self, name, age):
        self.name = name
        self.age = age
​
    def say(self):
        print(f"{self.name}在谈话")
​
​
p = Person("小明", 23)
复制代码

1 Check the object type

1.1 is series method

method illustrate
ismodule Check if object is a module
isclass Check if an object is a class
isfunction Check if an object is a function
ismethod Check if an object is a method
isbuiltin Check if an object is a built-in function or method

eg:

image-20220114111532345.png

import inspect
from test_study import driver_demo
​
print(inspect.ismodule(driver_demo))
复制代码

result:

True
复制代码
print(inspect.isfunction(test_func))
复制代码

result:

True
复制代码
print(inspect.isclass(Person))
print(inspect.ismethod(p.say))
复制代码

result:

True
True
复制代码
print(inspect.isbuiltin(print))
复制代码

result:

True
复制代码

1.2 isroutine method

Check whether the object is a callable type such as a function, method, built-in function or method, which is exactly the same as the is series

if inspect.isroutine(p.say):
    p.say()
复制代码

result:

小明在谈话
复制代码

1.3 Determining whether an object is callable

If you just judge whether the object is callable, you can take a simpler judgment method

from collections.abc import Callable


print(isinstance(p.say, Callable))
复制代码

result:

True
复制代码

2 Get object information

2.1 getmembers method

This method is an extended version of the dir() method

print(inspect.getmembers(p.say))
复制代码

result:

[('__call__', <method-wrapper '__call__' of method object at 0x0000020F307850C8>), ('__class__', <class 'method'>), ('__delattr__', <method-wrapper '__delattr__' of method object at 0x0000020F307850C8>), ('__dir__', <built-in method __dir__ of method object at 0x0000020F307850C8>), ('__doc__', None), ('__eq__', <method-wrapper '__eq__' of method object at 0x0000020F307850C8>), ('__format__', <built-in method __format__ of method object at 0x0000020F307850C8>), ('__func__', <function Person.say at 0x0000020F30E8C048>), ('__ge__', <method-wrapper '__ge__' of method object at 0x0000020F307850C8>), ('__get__', <method-wrapper '__get__' of method object at 0x0000020F307850C8>), ('__getattribute__', <method-wrapper '__getattribute__' of method object at 0x0000020F307850C8>), ('__gt__', <method-wrapper '__gt__' of method object at 0x0000020F307850C8>), ('__hash__', <method-wrapper '__hash__' of method object at 0x0000020F307850C8>), ('__init__', <method-wrapper '__init__' of method object at 0x0000020F307850C8>), ('__init_subclass__', <built-in method __init_subclass__ of type object at 0x00007FFE1190E030>), ('__le__', <method-wrapper '__le__' of method object at 0x0000020F307850C8>), ('__lt__', <method-wrapper '__lt__' of method object at 0x0000020F307850C8>), ('__ne__', <method-wrapper '__ne__' of method object at 0x0000020F307850C8>), ('__new__', <built-in method __new__ of type object at 0x00007FFE1190E030>), ('__reduce__', <built-in method __reduce__ of method object at 0x0000020F307850C8>), ('__reduce_ex__', <built-in method __reduce_ex__ of method object at 0x0000020F307850C8>), ('__repr__', <method-wrapper '__repr__' of method object at 0x0000020F307850C8>), ('__self__', <__main__.Person object at 0x0000020F30E89748>), ('__setattr__', <method-wrapper '__setattr__' of method object at 0x0000020F307850C8>), ('__sizeof__', <built-in method __sizeof__ of method object at 0x0000020F307850C8>), ('__str__', <method-wrapper '__str__' of method object at 0x0000020F307850C8>), ('__subclasshook__', <built-in method __subclasshook__ of type object at 0x00007FFE1190E030>)]
复制代码

2.2 getmodule method

The module name of the module where the class is located. Unlike the module method, the module name returned here is an object that can be called directly instead of a string.

print(inspect.getmodule(p.say))
复制代码

result:

<module '__main__' from 'D:/workspace/test_study/test_study/test.py'>
复制代码

2.3 getfile method

Get the filename defined by the object

print(inspect.getfile(p.say))
复制代码

result:

D:/workspace/test_study/test_study/test.py
复制代码

2.4 getsource method

Get the source code of an object

print(inspect.getsource(p.say))
复制代码

result:

def say(self):
    print(f"{self.name}在谈话")
复制代码

2.5 getfullargspec method

Get the parameters declared when the method is defined, and the result is a tuple, which are (normal parameter name list, *parameter name, **parameter name, default value tuple)

print(inspect.getfullargspec(test_func))
复制代码

result:

FullArgSpec(args=['name', 'age', 'sex'], varargs='ids', varkw='info', defaults=('男',), kwonlyargs=[], kwonlydefaults=None, annotations={})
复制代码

2.6 getargvalues ​​method

Only used for stack frame, get the parameter value of the current function call in stack frame, the result is a tuple, respectively (normal parameter name list, *parameter name, **parameter name, stack locals())

def test_func(name, age, sex="男", *ids, **info, ):
    """
    返回个人信息
    :param name: 姓名
    :param age: 年龄
    :param sex: 性别
    :return: 个人信息
    """
    print(inspect.getargvalues(inspect.currentframe()))
    return name + "," + age + "," + sex

print(test_func("小明", '23'))
复制代码

result:

ArgInfo(args=['name', 'age', 'sex'], varargs='ids', keywords='info', locals={'name': '小明', 'age': '23', 'sex': '男', 'ids': (), 'info': {}})
小明,23,男
复制代码

\

Guess you like

Origin juejin.im/post/7084027275519197197