本文翻译自: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), msgdef between(lo, hi):def _between(x):return lo <= x <= hi_between.__docstring__='must be between {} and {}'.format(lo,hi)       return _betweendef 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.5 , PEP 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/

-gt;在Python函数定义中是什么意思?相关推荐

  1. python函数定义中没有对参数指定类型、这说明_二级单选-函数和代码复用

    . i. .w. 1 关于递归函数的描述,以下选项中正确的是 A 函数部包含对本函数的再次调用 B 函数比较复杂 C 包含一个循环结构 D 函数名称作为返回值 正确答案: A 2 关于递归函数基例的说 ...

  2. python函数定义中参数列表里的参数是_详解Python函数中参数带星号是什么意思

    函数的参数使用除了常规的位置参数和关键字参数外,还支持可变个数的函数参数,这种支持可变个数的参数方法称为参数收集,对应的参数称为收集参数. 一.参数收集的定义 Python的函数支持可变不定数量的参数 ...

  3. python函数定义中参数列表里的参数是_python函数参数中的/和*是什么意思?

    在python3.8之后函数参数中允许出现/和*号,/用来指明某些函数形参必须使用位置参数而非关键字参数的形式,*出现在函数参数中第一种含义可以表示为可变参数,一般写作*args:对于单独出现在参数中 ...

  4. python函数定义中参数列表里的参数是_python-函数(def)参数 及参数解构 变量 知识整理...

    函数 python 函数 由若干语句组成的语句块.函数名称.参数列表构成,他是组织代码的最小单元 完成一定的功能 函数的作用: 结构化编程对代码的最基本的封装,一般按照功能组织一段代码 封装的目的是为 ...

  5. python函数定义中参数列表里的参数是_python函数定义中的参数说明

    原博文 2020-05-23 07:50 − > 描述函数定义时 涉及到的 位置参数,默认参数,关键字参数,可变参数等的概念及用法 ## 1 示例代码 ``` #! /usr/bin/env p ...

  6. python中的def是什么意思啊_在Python函数定义中-是什么意思?

    这些是PEP 3107中介绍的函数注释.具体来说,->标记返回函数注释. 示例:>>> def kinetic_energy(m:'in KG', v:'in M/S')-&g ...

  7. python函数参数定义_python函数定义中的5种参数

    python函数参数定义 Python函数定义中的5种参数类型: (5 Types of Arguments in Python Function Definition:) default argum ...

  8. 【python教程入门学习】Python函数定义及传参方式详解(4种)

    这篇文章主要介绍了Python函数定义及传参方式详解(4种),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧 一.函数初识 1.定 ...

  9. python系统提供构造函数传入参数_[ Python入门教程 ] Python函数定义和使用

    函数是一段可以重复多次调用的代码,通过输入的参数值,返回需要的结果.通过使用函数,可以提高代码的重复利用率.本文主要介绍Python函数的定义.调用和函数参数设置方法. 函数的定义 Python函数定 ...

最新文章

  1. totiseGit无法登录的问题
  2. VS2010中的调试技巧
  3. 惊天大谎:让穷人都能上网是Facebook的殖民阴谋?
  4. shiro的内部体系结构
  5. [多图/秒懂]白话OpenPose,最受欢迎的姿态估计网络
  6. 我所知道的Ribbon库
  7. Postman安装与使用(网络请求神器)--post、get请求
  8. mysql 备份脚本
  9. iOS博客 视频课程网站
  10. oracle时间加减的语句写法
  11. PLC编程:梯形图的转换设计法
  12. 怎么删除计算机c盘应用,C盘垃圾文件怎么删除,清理系统盘的电脑软件-腾讯电脑管家...
  13. NODE.JS对接验证码短信接口DEMO示例
  14. 一周信创舆情观察(1.10~1.16)
  15. 如何卸载腾讯云的云服务器主机安全云镜监控程序
  16. 【Vivado那些事儿】VIVADO中时序报告中WNS,WHS,TNS,THS含义
  17. 暗黑破坏神(DIABLOII 1.11B)BOT下载
  18. ccd摄像机基础知识
  19. Redis源码阅读笔记-动态字符串(SDS)结构
  20. Word 2016 撰写论文(3): 文献中常见的表格(三线表)制作

热门文章

  1. 马云为什么要卸任软银董事?开放和全球化的技术时代会终结吗
  2. 使用python爬虫爬取秒懂百科的视频
  3. 菜鸟码农一入行就拿百万年薪?2021硅谷巨头晒出霸气工资单!
  4. 互联网之达芬奇密码——信仰互联网
  5. Macbook pro 2015升级SSD
  6. MacBook Pro M1 Parallels Desktop 安装Win11
  7. enq:SQ-contention(SQ锁)测试
  8. 阿里巴巴:大数据总动员
  9. 计算机毕业设计Java物流管理系统(源码+系统+mysql数据库+Lw文档)
  10. Linux下电骡aMule Kademlia网络构建分析5 —— 资源的发布