什么是Python3的&QUOT良好的用途;功能注释" [英] What are good uses for Python3's "Function Annotations"

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

问题描述

功能注解: PEP-3107

我碰到code的展示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?

推荐答案

我觉得这其实是很大的。

I think this is actually great.

从学术背景的,我可以告诉你,说明已经证明了自己宝贵的启用智能静态分析仪像Java语言。例如,您可以定义像国家限制,被允许访问线程架构的局限性等语义,而且有相当多的工具,那么可以读取这些并处理它们提供超越您从编译器得到什么保证。你甚至可以写的东西检查preconditions /后置条件。

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。举例来说,我有一个工具,可以让您指派专人警告的方法,并为您的迹象,当你打电话给他们,你应该阅读它们的文档(例如,假设你有不能以负值调用的方法,但它的不从名称直观)。使用注释,我可以写technicall像这样为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 technicall 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的&QUOT良好的用途;功能注释"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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