->在Python函数定义中是什么意思?

本文翻译自:What does -> mean in Python function definitions?

I've recently noticed something interesting when looking at Python 3.3 grammar specification : 我最近在查看Python 3.3语法规范时发现了一些有趣的东西:

funcdef: 'def' NAME parameters ['->' test] ':' suite

The optional 'arrow' block was absent in Python 2 and I couldn't find any information regarding its meaning in Python 3. It turns out this is correct Python and it's accepted by the interpreter: 在Python 2中缺少可选的“箭头”块,并且在Python 3中找不到有关其含义的任何信息。事实证明这是正确的Python,并已被解释器接受:

def f(x) -> 123:
    return x

I thought that this might be some kind of a precondition syntax, but: 我认为这可能是某种前提语法,但是:

  • I cannot test x here, at it is still undefined, 我无法在此处测试x ,因为它仍未定义,
  • No matter what I put after the arrow (eg 2 < 1 ), it doesn't affect the function behaviour. 无论我在箭头后面加上什么(例如2 < 1 ),它都不会影响函数的行为。

Could anyone accustomed with this syntax explain it? 习惯此语法的任何人都可以解释吗?


#1楼

参考:https://stackoom.com/question/yKpV/gt-在Python函数定义中是什么意思


#2楼

It's a function annotation . 这是一个功能注释

In more detail, Python 2.x has docstrings, which allow you to attach a metadata string to various types of object. 更详细地讲,Python 2.x具有文档字符串,使您可以将元数据字符串附加到各种类型的对象。 This is amazingly handy, so Python 3 extends the feature by allowing you to attach metadata to functions describing their parameters and return values. 这非常方便,因此Python 3通过允许您将元数据附加到描述其参数和返回值的函数来扩展了该功能。

There's no preconceived use case, but the PEP suggests several. 没有预想的用例,但是PEP建议了几个。 One very handy one is to allow you to annotate parameters with their expected types; 一种非常方便的方法是允许您使用期望的类型注释参数。 it would then be easy to write a decorator that verifies the annotations or coerces the arguments to the right type. 这样就很容易编写一个装饰器来验证注释或将参数强制为正确的类型。 Another is to allow parameter-specific documentation instead of encoding it into the docstring. 另一个是允许特定于参数的文档,而不是将其编码为文档字符串。


#3楼

These are function annotations covered in PEP 3107 . 这些是PEP 3107中涵盖的功能注释。 Specifically, the -> marks the return function annotation. 具体来说, ->标记返回函数注释。

Examples: 例子:

>>> 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'}

Annotations are dictionaries, so you can do this: 注释是字典,因此您可以执行以下操作:

>>> '{:,} {}'.format(kinetic_energy(20,3000),
      kinetic_energy.__annotations__['return'])
'90,000,000.0 Joules'

You can also have a python data structure rather than just a string: 您还可以拥有一个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'

Or, you can use function attributes to validate called values: 或者,您可以使用函数属性来验证调用的值:

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)

Prints 版画

>>> f(2,2) 
AssertionError: x==2; Test: _between: must be between 3 and 10
>>> f(3,2.1)
AssertionError: y==2.1; Test: <lambda>

#4楼

As other answers have stated, the -> symbol is used as part of function annotations. 正如其他答案所说, ->符号用作功能注释的一部分。 In more recent versions of Python >= 3.5 , though, it has a defined meaning. 不过,在最新版本的Python >= 3.5 ,它具有定义的含义。

PEP 3107 -- Function Annotations described the specification, defining the grammar changes, the existence of func.__annotations__ in which they are stored and, the fact that it's use case is still open. PEP 3107-函数注释描述了规范,定义了语法更改, func.__annotations__存储在其中的func.__annotations__以及用例的事实仍然开放。

In Python 3.5 though, PEP 484 -- Type Hints attaches a single meaning to this: -> is used to indicate the type that the function returns. 但是在Python 3.5PEP 484-类型提示对此附加了一个含义: ->用于指示函数返回的类型。 It also seems like this will be enforced in future versions as described in What about existing uses of annotations : 看起来这将在将来的版本中强制执行,如注释的现有用法如何

The fastest conceivable scheme would introduce silent deprecation of non-type-hint annotations in 3.6, full deprecation in 3.7, and declare type hints as the only allowed use of annotations in Python 3.8. 最快的可能方案将在3.6中引入对非类型隐式注释的无提示弃用,在3.7中引入全弃用,并将类型提示声明为Python 3.8中唯一允许使用的注释。

(Emphasis mine) (强调我的)

This hasn't been actually implemented as of 3.6 as far as I can tell so it might get bumped to future versions. 据我所知,从3.6开始实际上尚未实现此功能,因此可能会与将来的版本发生冲突。

According to this, the example you've supplied: 据此,您提供了示例:

def f(x) -> 123:
    return x

will be forbidden in the future (and in current versions will be confusing), it would need to be changed to: 将来会被禁止(并且在当前版本中会令人困惑),因此需要将其更改为:

def f(x) -> int:
    return x

for it to effectively describe that function f returns an object of type int . 为了有效地描述函数f返回一个int类型的对象。

The annotations are not used in any way by Python itself, it pretty much populates and ignores them. Python本身不以任何方式使用这些注释,它几乎填充并忽略了它们。 It's up to 3rd party libraries to work with them. 与他们合作的取决于第三方图书馆。


#5楼

def function(arg)->123:

It's simply a return type, integer in this case doesn't matter which number you write. 它只是一个返回类型,在这种情况下, 整数与您写入的数字无关紧要。

like Java : Java一样:

public int function(int args){...}

But for Python (how Jim Fasarakis Hilliard said) the return type it's just an hint , so it's suggest the return but allow anyway to return other type like a string.. 但是对于Python( Jim Fasarakis Hilliard怎么说) ,返回类型只是一个提示 ,因此建议返回,但是无论如何都允许返回其他类型,例如字符串。


#6楼

Python ignores it. Python会忽略它。 In the following code: 在下面的代码中:

def f(x) -> int:
    return int(x)

the -> int just tells that f() returns an integer. -> int只是告诉f()返回一个整数。 It is called a return annotation , and can be accessed as f.__annotations__['return'] . 它称为return注解 ,可以作为f.__annotations__['return']

Python also supports parameter annotations: Python还支持参数注释:

def f(x: float) -> int:
    return int(x)

: float tells people who read the program (and some third-party libraries/programs, eg pylint) that x should be a float . : float告诉阅读程序(和某些第三方库/程序,例如pylint)的人们x应该是float Itis accessed as f.__annotations__['x'] , and doesn't have any meaning by itself. 它以f.__annotations__['x'] ,并且本身没有任何意义。 See the documentation for more information: 请参阅文档以获取更多信息:

https://docs.python.org/3/reference/compound_stmts.html#function-definitions https://www.python.org/dev/peps/pep-3107/ https://docs.python.org/3/reference/compound_stmts.html#function-definitions https://www.python.org/dev/peps/pep-3107/

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值