python-inspect module

Common functions of inspect module

import inspect  # Import inspect module
inspect.isfunction(fn)   # Detecting whether fn is a function
inspect.isgenerator((x for x in range(10)))  # Check if it's a generator
inspect.isclass(int)   # Check if int is a class
inspect.isbuiltin(print)  # Check if print is built-in function
import random
inspect.ismodule  # Detecting whether random is a module

We take inspect. signature (function) and analyze it separately, as follows:

def add(x: int, y: int):  # Define a function
	return x + y
import inspect
sig = inspect.signature(add)  # Get the parameter signature of a function
print(sig)    # (x: int, y: int)
parms = sig.parameters
print(parms)  # Print an ordered dictionary. The key of the dictionary is the formal parameter of the add function. The values of the dictionary are the various attributes corresponding to the formal parameter key of the function. Let's learn its annotation attribute.
# OrderedDict([('x', <Parameter "x: int">), ('y', <Parameter "y: int">)])
print(parms['x'].annotation)  # The annotation type of <class'int'> parameter x is int

Application-Business Practice

Through the above analysis, we learned how to get annotation information of a function. Now we want to achieve a business:
Function parameter type checking, which automatically checks the incoming actual parameters and the annotations of the parameters when the parameters are invoked, and gives hints if they are different.

Thought: - Function parameter checking, preferably outside the function, you can think of using decorator
-_ The annotation_ attribute is a dictionary

import inspect
from functools import wraps
def logger(fn):
    d = {}
    @wraps(fn)
    def wrapper(*args, **kwargs):
        print(kwargs)
        sig = inspect.signature(fn)
        params = sig.parameters
        print(params)
        for i,v in enumerate(params.values()):
            d[f'{i}'] = v.annotation
        for i,x in enumerate(args):
            if d[f'{i}'] == 'inspect._empty' or type(x) == d[f'{i}']:
                print(x, 'very okļ¼ŒThat's all right.')
            else:
                print(x, 'Wrong type')
        for k,v in kwargs.items():
            if type(v) == params[k].annotation:
                print(v,'ok,Sure')
            else:
                print(v,'No way')
        ret = fn(*args, **kwargs)
       # print(d)
        # print(d['1'])
        return ret
    return wrapper
@logger
def add(x:str, y:int=7)->int:
    return x + y
add(3,y='sdf')

Keywords: Attribute

Added by whiterecluse on Mon, 30 Sep 2019 22:32:28 +0300