Python3的“函数注释"有什么好的用途? [英] What are good uses for Python3's "Function Annotations"?

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

问题描述

功能注释: PEP-3107

我碰到了一段代码,展示了Python3的功能注释.这个概念很简单,但我想不出为什么要在Python3中实现这些功能或对其有什么好处.也许可以启发我吗?

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的“函数注释"有什么好的用途?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆