装逼利器函数注释
说实话两年来,我从来没有如此的关注过注释,不说话先上代码
def add(a, b) -> 0: result = a + b add.__annotations__['return'] += result return result print(add.__annotations__['return']) #0 add(3, 4) print(add.__annotations__['return']) #7 add(5, 5) print(add.__annotations__['return']) #10
这是python3.3的新的函数注释方式,不支持2,亲试
具体可以有下面三种方式
方式一: 下面的注释参数m:后面是注释,v:后面是注释,->后面是返回值
>>> def kinetic_energy(m:'in KG', v:'in M/S')->'Joules': ... return 1/2*m*v**2 ... >>> kinetic_energy.__annotations__ {'return': 'Joules', 'v': 'in M/S', 'm': 'in KG'}
方式二:注释可以为返回值
>>> rd={'type':float,'units':'Joules','docstring':'Given mass and velocity returns kinetic energy in Joules'} >>> def f()->rd: ... pass >>> f.__annotations__['return']['type'] <class 'float'> >>> f.__annotations__['return']['units'] 'Joules' >>> f.__annotations__['return']['docstring'] 'Given mass and velocity returns kinetic energy in Joules'
方式三:
def validate(func, locals): for var, test in func.__annotations__.items(): value = locals[var] try: pr=test.__name__+': '+test.__docstring__ except AttributeError: pr=test.__name__ msg = '{}=={}; Test: {}'.format(var, value, pr) assert test(value), msg def between(lo, hi): def _between(x): return lo <= x <= hi _between.__docstring__='must be between {} and {}'.format(lo,hi) return _between def f(x: between(3,10), y:lambda _y: isinstance(_y,int)): validate(f, locals()) print(x,y)
>>> f(2,2)
AssertionError: x==2; Test: _between: must be between 3 and 10
>>> f(3,2.1)
AssertionError: y==2.1; Test: <lambda>
方法总结:
1、在参数后面加注释,可以替代常规默认参数
2、函数名括号后面是返回值对应的value,相当于函数的默认返回值
3、通过__annotations__ 来获取所有的注释信息
通过上面的代码示例,开头代码就总结了几乎所有方法
def add(a:1, b:"aaa") -> 0: result = a + b add.__annotations__['return'] += result return result print(add.__annotations__['return']) print(add.__annotations__.items()) add(3, 4) print(add.__annotations__['return']) add(5, 5) print(add.__annotations__['return'])
打印结果:
0
dict_items([('b', 'aaa'), ('return', 0), ('a', 1)])
7
17
为什么这种注释方式我如此的重视?
这种逆天的注释方式,不再是常规的文本方式注释用来解释,而是以一种反射的机制来进行注释,真正做到灵活多变物尽其用
一句话:
They have the potential to usher in a new era of introspective tools that help developers master more and more complex systems. They also offer the more advanced developer a standard and readable way to associate metadata directly with arguments and return value in order to create custom tools and interact with decorators.