Make writing a habit together! This is the sixth day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

The inspect module provides a series of functions for introspection operations. Here’s the narrative.

The classes and functions involved are as follows:

Def test_func(name, age, sex=" male ", *ids, **info): "def test_func(name, age, sex=" male ", *ids, **info): "" "" 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(" self.name ", 23)Copy the code

Procedure 1 Check the object type

1.1 IS series methods

methods instructions
ismodule Check whether the object is a module
isclass Check whether the object is a class
isfunction Checks whether the object is a function
ismethod Checks whether the object is a method
isbuiltin Checks whether the object is a built-in function or method

eg:

import inspect
from test_study import driver_demo
​
print(inspect.ismodule(driver_demo))
Copy the code

result:

True
Copy the code
print(inspect.isfunction(test_func))
Copy the code

result:

True
Copy the code
print(inspect.isclass(Person))
print(inspect.ismethod(p.say))
Copy the code

result:

True
True
Copy the code
print(inspect.isbuiltin(print))
Copy the code

result:

True
Copy the code

1.2 isroutine method

Checking whether an object is a callable type such as a function, method, built-in function, or method is exactly the same as the IS family

if inspect.isroutine(p.say):
    p.say()
Copy the code

result:

Xiao Ming is talkingCopy the code

1.3 Checking whether an object is callable

If you’re just trying to determine whether an object is callable, you can take a simpler approach

from collections.abc import Callable


print(isinstance(p.say, Callable))
Copy the code

result:

True
Copy the code

2 Obtain object information

2.1 getmembers method

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

print(inspect.getmembers(p.say))
Copy the code

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>)]
Copy the code

2.2 getmodule method

The module name of the module in which the class resides. Unlike the module method, the module name returned here is an object that can be called directly rather than as a string

print(inspect.getmodule(p.say))
Copy the code

result:

<module '__main__' from 'D:/workspace/test_study/test_study/test.py'>
Copy the code

2.3 getfile method

Gets the file name defined by the object

print(inspect.getfile(p.say))
Copy the code

result:

D:/workspace/test_study/test_study/test.py
Copy the code

2.4 getsource method

Get the source code for the object

print(inspect.getsource(p.say))
Copy the code

result:

Def say(self): print(f"{self.name} ")Copy the code

2.5 getfullargspec method

Gets the arguments declared when the method is defined. The result is a tuple of (common parameter names, * parameter names, ** parameter names, default tuples)

print(inspect.getfullargspec(test_func))
Copy the code

result:

FullArgSpec (args = [' name ', 'age', 'sex'], varargs = 'ids', varkw =' info ', defaults = (' male '), kwonlyargs = [], kwonlydefaults=None, annotations={})Copy the code

2.6 getargvalues method

Gets the parameter values of the function currently called in the frame. The result is a tuple of (common parameter names, * parameter names, ** parameter names, and stack locals()).

Def test_func(name, age, sex=" male ", *ids, **info,): def test_func(name, age, sex=" male ", *ids, **info,): Print (inspect.getargvalues(inspect.currentFrame ())) return name + "," + age + "," + sex print(test_func(" test_func ", '23'))Copy the code

result:

ArgInfo (args = [' name ', 'age', 'sex'], varargs = 'ids', keywords =' info ', locals = {' name ':' xiao Ming ', 'age', '23', 'sex' : 'male ', 'ids': (), 'info': {}}) Xiao Ming,23, maleCopy the code

\