Kro*_*ton 383 python annotations python-3.x function-definition
在查看Python 3.3语法规范时,我最近发现了一些有趣的东西:
funcdef: 'def' NAME parameters ['->' test] ':' suite
Run Code Online (Sandbox Code Playgroud)
Python 2中没有可选的"箭头"块,我在Python 3中找不到任何有关其含义的信息.事实证明这是正确的Python并且它被解释器接受:
def f(x) -> 123:
return x
Run Code Online (Sandbox Code Playgroud)
我认为这可能是某种先决条件语法,但是:
x在这里测试,它仍未定义,2 < 1),它都不会影响功能行为.任何习惯这种语法的人都可以解释一下吗?
Kat*_*iel 299
这是一个功能注释.
更详细地说,Python 2.x具有docstrings,允许您将元数据字符串附加到各种类型的对象.这非常方便,因此Python 3通过允许您将元数据附加到描述其参数和返回值的函数来扩展该功能.
没有先入为主的用例,但PEP提出了几个建议.一个非常方便的方法是允许您使用预期类型注释参数; 然后很容易编写一个装饰器来验证注释或强制正确类型的参数.另一种方法是允许特定于参数的文档,而不是将其编码到docstring中.
daw*_*awg 198
这些是PEP 3107中涵盖的功能注释.具体来说,->标记返回函数注释.
例子:
>>> 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'}
Run Code Online (Sandbox Code Playgroud)
注释是字典,因此您可以这样做:
>>> '{:,} {}'.format(kinetic_energy(20,3000),
kinetic_energy.__annotations__['return'])
'90,000,000.0 Joules'
Run Code Online (Sandbox Code Playgroud)
你也可以有一个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'
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用函数属性来验证调用值:
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)
Run Code Online (Sandbox Code Playgroud)
打印
>>> f(2,2)
AssertionError: x==2; Test: _between: must be between 3 and 10
>>> f(3,2.1)
AssertionError: y==2.1; Test: <lambda>
Run Code Online (Sandbox Code Playgroud)
Jim*_*ard 75
正如其他答案所述,该->符号用作功能注释的一部分.>= 3.5但是,在更新版本的Python中,它具有已定义的含义.
PEP 3107 - 功能注释描述了规范,定义了语法变化,func.__annotations__存储它们的存在以及它的用例仍然是开放的这一事实.
但是在Python中3.5,PEP 484 - Type Hints附加了一个含义:->用于指示函数返回的类型.它似乎也将在未来版本中强制执行,如注释的现有用法:
最快的可想到的方案将引入静态弃用3.6中的非类型提示注释,3.7中的完全弃用,并声明类型提示作为Python 3.8中唯一允许使用的注释.
(强调我的)
3.6到目前为止,我还没有真正实现这一点,因此它可能会受到未来版本的影响.
根据这个,您提供的示例:
def f(x) -> 123:
return x
Run Code Online (Sandbox Code Playgroud)
将来会被禁止(并且在当前版本中会令人困惑),需要将其更改为:
def f(x) -> int:
return x
Run Code Online (Sandbox Code Playgroud)
为了它有效地描述该函数f返回一个类型的对象int.
Python本身并没有以任何方式使用注释,它几乎填充并忽略它们.由第三方库来决定它们.
Max*_*use 21
Python会忽略它。在下面的代码中:
def f(x) -> int:
return int(x)
Run Code Online (Sandbox Code Playgroud)
在-> int刚刚告诉f()返回一个整数。它称为返回注释,可以通过进行访问f.__annotations__['return']。
Python还支持参数注释:
def f(x: float) -> int:
return int(x)
Run Code Online (Sandbox Code Playgroud)
: float告诉阅读该程序(和某些第三方库/程序,例如pylint)的人员x应为float。它以形式访问f.__annotations__['x'],其本身没有任何意义。请参阅文档以获取更多信息:
https://docs.python.org/3/reference/compound_stmts.html#function-definitions https://www.python.org/dev/peps/pep-3107/
小智 11
def f(x) -> str:
return x+4
print(f(45))
Run Code Online (Sandbox Code Playgroud)
将给出结果:49。
或者换句话说 '-> str' 对返回类型没有影响:
print(f(45).__class__)
<class 'int'>
Run Code Online (Sandbox Code Playgroud)
def function(arg)->123:
它只是一个返回类型,在这种情况下整数与您写的数字无关。
像Java:
public int function(int args){...}
Run Code Online (Sandbox Code Playgroud)
但是对于 Python(Jim Fasarakis Hilliard怎么说) ,返回类型只是一个提示,因此建议返回但允许返回其他类型,如字符串。
小智 7
这意味着函数返回的结果类型,但它可以是 None.
它在面向 Python 3.x 的现代库中很普遍。
例如,它在很多地方的库pandas-profiling的代码中都有,例如:
def get_description(self) -> dict:
def get_rejected_variables(self, threshold: float = 0.9) -> list:
def to_file(self, output_file: Path or str, silent: bool = True) -> None:
"""Write the report to a file.
Run Code Online (Sandbox Code Playgroud)
小智 7
def f(x) -> 123:
return x
Run Code Online (Sandbox Code Playgroud)
我的总结:
->引入Simply是为了让开发人员可以选择指定函数的返回类型。参见Python 增强提案 3107
这表明随着 Python 的广泛采用,未来可能会如何发展——这是对强类型的一种暗示——这是我个人的观察。
您也可以为参数指定类型。指定函数和参数的返回类型将有助于减少逻辑错误和改进代码增强。
您可以将表达式作为返回类型(对于函数和参数级别),并且可以通过注释对象的“返回”属性访问表达式的结果。lambda 内联函数的表达式/返回值的注释将为空。