これらは、PEP 3107で扱われる機能注釈です。具体的には、->
はreturn関数アノテーションをマークします。
例:
>>> '{:,} {}'.format(kinetic_energy(20,3000),
kinetic_energy.__annotations__['return'])
'90,000,000.0 Joules'
ます。また、Pythonのデータ構造を持つことができるだけではなく、文字列:
>>> 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 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'}
、あなたはこれを行うことができますので、
または、関数属性を使用して呼び出された値を検証することができます。
他の回答として
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)
プリント
この情報は '.__ annotations__'属性として利用できます。 –
うわー、私は知識の広範な領域を欠場しました。値の注釈だけでなく、パラメータ注釈も返します。どうもありがとうございました :)。 – Krotton
@Krottonそれを見逃したことにあなたを責めることはできませんが、実際には使用されていません。私はそれらを使って1つのライブラリにしか会ったことがなく、それはかなりわかりません。 – delnan