本文介绍了Python3 的“函数注解"有什么好的用处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数注释: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}

提供此功能有什么意义?

What's the significance of having this available?

推荐答案

我觉得这真的很棒.

从学术背景来看,我可以告诉您,注释已被证明对于为 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 的“函数注解"有什么好的用处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 03:46