什么 - >在Python函数定义中意味着什么?

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中.

  • 这些信息以`.__ annotations__`属性的形式提供. (99认同)
  • @delnan - 可能是它大部分未被使用的原因是因为大多数python库仍然旨在与python2.x兼容.随着python3.x开始变得更加标准,我们可能会看到更多这些东西在这里和那里出现...... (9认同)
  • 哇,我错过了很广泛的知识领域 - 不仅包括返回值注释,还包括参数注释.非常感谢你 :). (7认同)
  • 而`__annotations__`属性是一本字典.键"return"是用于检索箭头后面的值的键. (4认同)
  • @Krotton不能责怪你错过它,它几乎没用过.我只遇到过使用它们的单个库,而且它非常模糊. (3认同)

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)

  • 我认为这是一个完整的例子。 (7认同)

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)


Mik*_*son 8

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)

我的总结:

  1. ->引入Simply是为了让开发人员可以选择指定函数的返回类型。参见Python 增强提案 3107

  2. 这表明随着 Python 的广泛采用,未来可能会如何发展——这是对强类型的一种暗示——这是我个人的观察。

  3. 您也可以为参数指定类型。指定函数和参数的返回类型将有助于减少逻辑错误和改进代码增强。

  4. 您可以将表达式作为返回类型(对于函数和参数级别),并且可以通过注释对象的“返回”属性访问表达式的结果。lambda 内联函数的表达式/返回值的注释将为空。


小智 5

->是在python3中引入的。

简单来说,->后面的内容表示函数的返回类型。返回类型是可选的。

  • 此答案中的指导与之前发布的答案中的指导有何不同? (2认同)