Python 函数注释有什么好处? [英] What good are Python function annotations?

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

问题描述

我已经阅读了 PEP 3107 中的前几个部分,但我仍然不明白它们对语言有什么好处.在我看来,您可以使用装饰器向函数添加元数据.例如

I have gone through the first couple of sections in PEP 3107, but I still don't get what good they do for the language. It seems to me that you can add metadata to functions using decorators. e.g.

def returns(return_type):
  f.return_type = return_type  # <- adding metadata here
  return f

@returns(Foo)
def make_foo(): ...

您也可以向参数添加元数据,如果您利用默认参数,它看起来会很漂亮,如下所示:

You can add metadata to arguments too, and it can look pretty if you take advantage of default arguments, like so:

import inspect

def defaults_are_actually_metadata(f):
  names, args_name, kwargs_name, defaults = inspect.getfuncspec(f)
  f.parameter_metadata = dict(zip(names[-len(defaults):], defaults))
  f.__defaults__ = ()
  return f

@defaults_are_actually_metadata
def haul(load="Stuff to be carried.",
         speed_mph="How fast to move the load (in miles per hour)."): ...

至少我最初的印象是注解是多余的:装饰者可以做注解所能做的一切(甚至更多).为什么在向函数添加元数据时注解比装饰器更好?

At least my initial impression is that annotations are superfluous: decorators can do everything that annotations can (and more). Why are annotations better than decorators when it comes to adding metadata to functions?

推荐答案

如你所说,相关的 PEP 是 3107(链接以方便参考,以防遇到此问题的其他人尚未阅读).

As you mentioned, the relevant PEP is 3107 (linked for easy reference in case others encountering this question haven't read it yet).

就目前而言,注释是一种实验,一种正在进行的工作.python-ideas邮件列表 关于可能有帮助的主题.(提供的链接仅用于每月存档;我发现特定帖子的 URL 往往会定期更改.有问题的线程在 12 月初附近,标题为[Python-ideas] 函数注释约定".第一个帖子来自 Thomas Kluyver 于 12 月 1 日.)

For now, annotations are kind of an experiment, and kind of a work in progress. There is actually a recent thread in the python-ideas mailing list on the topic which may be helpful. (The link provided is just for the monthly archive; I find that the URL for specific posts tends to change periodically. The thread in question is near the beginning of December, and titled "[Python-ideas] Conventions for function annotations". The first post is from Thomas Kluyver on Dec 1.)

以下是该主题中 Guido van Rossum 的一篇帖子的一些内容:

Here's a bit from one of Guido van Rossum's posts in that thread:

在 12/4/2012 上午 11:43,Jasper St. Pierre 写道:

On 12/4/2012 11:43 AM, Jasper St. Pierre wrote:

确实如此.我以前看过注释,但我从来没有理解目的.这似乎是一个没有设计和实现的功能心中有一些目标,以及社区应该在哪里发现目标自己.

Indeed. I've looked at annotations before, but I never understood the purpose. It seemed like a feature that was designed and implemented without some goal in mind, and where the community was supposed to discover the goal themselves.

Guido 的回应:

恰恰相反.有太多的用例立即看起来重要,我们无法弄清楚哪些是最重要的重要或如何组合它们,所以我们决定采取两步方法:在步骤 1 中,我们设计了语法,而在步骤 2 中,我们将设计语义.这个想法很清楚,一旦语法已经确定,人们可以自由地尝试不同的语义——只是不在标准库中.这个想法也是最终,从所有这些实验中,会出现一个适合标准库.

To the contrary. There were too many use cases that immediately looked important, and we couldn't figure out which ones would be the most important or how to combine them, so we decided to take a two-step approach: in step 1, we designed the syntax, whereas in step 2, we would design the semantics. The idea was very clear that once the syntax was settled people would be free to experiment with different semantics -- just not in the stdlib. The idea was also that eventually, from all those experiments, one would emerge that would be fit for the stdlib.

贾斯珀·圣皮埃尔:

那么,如果我可以问,注释的最初目标是什么?PEP 给出一些建议,但没有留下任何具体内容.是不是被设计成对 IDE 或检查源代码的静态分析工具的帮助?某物应用程序本身可以通过提供特殊行为,像命令行解析器,还是运行时静态检查器?

So, if I may ask, what was the original goal of annotations? The PEP gives some suggestions, but doesn't leave anything concrete. Was it designed to be an aid to IDEs, or static analysis tools that inspect source code? Something for applications themselves to munge through to provide special behaviors, like a command line parser, or runtime static checker?

Guido 的回应:

在某种程度上几乎所有上述内容.但就我个人而言,主要目标始终是达到指定类型的符号参数和返回的约束(也可能是其他约束)值.我在不同的时间玩弄了特定的组合方式类型.例如.list[int] 可能意味着一个整数列表,而 dict[str,tuple[float, float, float, bool]] 可能意味着一个字典将字符串映射到三个浮点数和一个布尔值的元组.但我觉得很难就这样的符号达成共识,而不是就参数的语法达成共识注释(想想你可以对这些提出多少反对意见两个例子 :-) -- 我一直强烈希望使用 "var: type= default" 并使类型成为要计算的运行时表达式同时作为默认值.

Pretty much all of the above to some extent. But for me personally, the main goal was always to arrive at a notation to specify type constraints (and maybe other constraints) for arguments and return values. I've toyed at various times with specific ways of combining types. E.g. list[int] might mean a list of integers, and dict[str, tuple[float, float, float, bool]] might mean a dict mapping strings to tuples of three floats and a bool. But I felt it was much harder to get consensus about such a notation than about the syntax for argument annotations (think about how many objections you can bring in to these two examples :-) -- I've always had a strong desire to use "var: type = default" and to make the type a runtime expression to be evaluated at the same time as the default.

还有一点来自 Ned Batchelder 的幽默:

And a tiny bit of humor from Ned Batchelder:

对我来说一个重要的时刻是在 PyCon 的早期 Py3k 主题演讲中(也许是是在达拉斯还是芝加哥?),Guido 不记得这个词了注释,"然后说,你知道,那些不是打字的东西声明?" :-)

A telling moment for me was during an early Py3k keynote at PyCon (perhaps it was in Dallas or Chicago?), Guido couldn't remember the word "annotation," and said, "you know, those things that aren't type declarations?" :-)

这篇关于Python 函数注释有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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