问题描述
函数注释:PEP-3107
我遇到了一段演示 Python3 函数注释的代码片段.这个概念很简单,但我想不出为什么这些是在 Python3 中实现的,或者它们有什么好的用途.也许SO可以启发我?
I ran across a snippet of code demonstrating Python3's function annotations. The concept is simple but I can't think of why these were implemented in Python3 or any good uses for them. Perhaps SO can enlighten me?
它是如何工作的:
def foo(a: 'x', b: 5 + 6, c: list) -> max(2, 9):
... function body ...
参数后冒号后面的所有内容都是注解",->
后面的信息是函数返回值的注解.
Everything following the colon after an argument is an 'annotation', and the information following the ->
is an annotation for the function's return value.
foo.func_annotations 会返回一个字典:
foo.func_annotations would return a dictionary:
{'a': 'x',
'b': 11,
'c': list,
'return': 9}
提供这个有什么意义?
推荐答案
我觉得这真的很棒.
来自学术背景,我可以告诉您,注释已证明它们对于为 Java 等语言启用智能静态分析器非常宝贵.例如,您可以定义诸如状态限制、允许访问的线程、架构限制等语义,并且有相当多的工具可以读取并处理它们,以提供超出您从编译器获得的保证的保证.你甚至可以编写检查前置条件/后置条件的东西.
Coming from an academic background, I can tell you that annotations have proved themselves invaluable for enabling smart static analyzers for languages like Java. For instance, you could define semantics like state restrictions, threads that are allowed to access, architecture limitations, etc., and there are quite a few tools that can then read these and process them to provide assurances beyond what you get from the compilers. You could even write things that check preconditions/postconditions.
我觉得在 Python 中尤其需要这样的东西,因为它的类型较弱,但实际上没有任何结构可以让这种简单直接成为官方语法的一部分.
I feel something like this is especially needed in Python because of its weaker typing, but there were really no constructs that made this straightforward and part of the official syntax.
除了保证之外,注释还有其他用途.我可以看到如何将基于 Java 的工具应用到 Python.例如,我有一个工具可以让您为方法分配特殊警告,并在您调用它们时提示您应该阅读它们的文档(例如,假设您有一个不能以负值调用的方法,但它是从名称上看不直观).使用注释,我可以在技术上为 Python 编写类似的东西.同样的,如果有官方的语法,也可以写出一个基于标签组织大类中方法的工具.
There are other uses for annotations beyond assurance. I can see how I could apply my Java-based tools to Python. For instance, I have a tool that lets you assign special warnings to methods, and gives you indications when you call them that you should read their documentation (E.g., imagine you have a method that must not be invoked with a negative value, but it's not intuitive from the name). With annotations, I could technically write something like this for Python. Similarly, a tool that organizes methods in a large class based on tags can be written if there is an official syntax.
这篇关于Python3 的“函数注释"有什么好的用途?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!