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

2024-05-17 01:01:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近在看Python 3.3 grammar specification时注意到一些有趣的东西:

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

Python 2中没有可选的“arrow”块,我在Python 3中找不到任何关于它的含义的信息。原来这是正确的Python,解释器接受了它:

def f(x) -> 123:
    return x

我认为这可能是某种先决条件语法,但是:

  • 我无法在这里测试x,因为它仍然是未定义的
  • 不管我在箭头后面放什么(例如2 < 1),它都不会影响函数行为。

熟悉这种语法的人能解释一下吗?


Tags: nametest信息return先决条件def语法解释器
3条回答

如其他答案所述,->符号用作函数注释的一部分。不过,在Python>= 3.5的较新版本中,它有一个定义为含义。

PEP 3107 -- Function Annotations描述了规范,定义了语法更改,存储这些更改的func.__annotations__的存在,以及它的用例仍然打开的事实。

不过,在Python中,PEP 484 -- Type Hints只附加了一个含义:->用于指示函数返回的类型。这似乎也将在将来的版本中强制执行,如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为止,这实际上还没有实现,因此可能会被推迟到将来的版本。

根据这一点,您提供的示例:

def f(x) -> 123:
    return x

将在将来被禁止(在当前版本中会令人困惑),需要将其更改为:

def f(x) -> int:
    return x

为了有效地描述函数f返回类型为int的对象。

Python本身并没有以任何方式使用注释,它会填充并忽略它们。这取决于第三方图书馆与他们合作。

是一个function annotation

更详细地说,Python2.x有docstrings,它允许您将元数据字符串附加到各种类型的对象。这非常方便,因此Python 3通过允许您将元数据附加到描述其参数和返回值的函数来扩展该特性。

没有先入为主的用例,但是PEP建议了几个。一个非常方便的方法是允许您使用参数的预期类型对其进行注释;然后编写一个decorator来验证注释或将参数强制为正确的类型就很容易了。另一种方法是允许特定于参数的文档,而不是将其编码为docstring。

这些是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'}

注释是字典,因此您可以执行以下操作:

>>> '{:,} {}'.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 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>

相关问题 更多 >