实用:python中函数的注解/签名(稽核函数inspect使用)

import inspect
def add(x:int=0,y:int=0,*args,z:int=0,**kwargs) ->int:
    '''
    this is a function for add
    x: int
    y: int
    return: int
    '''
    return x + y

print(add(4,5))
print(add('a','b'))
print(add())
print(add.__annotations__)

print('-'*50)
sig  = inspect.signature(add)
print(sig)

print('-'*50)
print('parameter:',sig.parameters)
print('x:',sig.parameters['x'])
print('z:',sig.parameters['z'].annotation)    #参数注解
print('z:',sig.parameters['z'].name)   #参数名字
print('z:',sig.parameters['z'].default)  #参数默认值

print('-'*50)
print('z:',sig.parameters['z'].kind)   #参数类型
print('x:',sig.parameters['x'].kind)
print('args:',sig.parameters['args'].kind)
print('kwargs:',sig.parameters['kwargs'].kind)

print('-'*50)
print('args:',sig.parameters['args'].annotation)   #可变类型注解为空
print('return:',sig.return_annotation)

运行结果:

9
ab
0
{'return': , 'y': , 'z': , 'x': }
--------------------------------------------------
(x:int=0, y:int=0, *args, z:int=0, **kwargs) -> int
--------------------------------------------------
parameter: OrderedDict([('x', ), ('y', ), ('args', ), ('z', ), ('kwargs', )])
x: x:int=0
z: 
z: z
z: 0
--------------------------------------------------
z: KEYWORD_ONLY
x: POSITIONAL_OR_KEYWORD
args: VAR_POSITIONAL
kwargs: VAR_KEYWORD
--------------------------------------------------
args: 
return: 

继续查看元素:

for i,item in enumerate(sig.parameters.items()):
    k,v = item
    print(i,item)
    print(i,k,v)

运行结果:

0 ('x', )
0 x x:int=0
1 ('y', )
1 y y:int=0
2 ('args', )
2 args *args
3 ('z', )
3 z z:int=0
4 ('kwargs', )
4 kwargs **kwargs

inspect稽核函数的使用:

import inspect
import functools


def add1():
    pass
    
class add2():
    @classmethod
    def count():
        pass
    
def add3(x):
    for i in range(5):
        yield x+i
        
add4 = add3(3)

print(1,inspect.isfunction(add1))
print(2,inspect.isclass(add2))
print(3,inspect.ismethod(add2.count))
print(4,inspect.isgeneratorfunction(add3))
print(5,inspect.isgenerator(add4))
print(6,inspect.ismodule(functools))
print(7,inspect.isbuiltin(print))

运行结果:

1 True
2 True
3 True
4 True
5 True
6 True
7 True

你可能感兴趣的:(python,Python学习记录)