[New-bugs-announce] [issue14893] Tutorial: Add function annotation example to function tutorial

Zachary Ware report at bugs.python.org
Wed May 23 21:42:35 CEST 2012


New submission from Zachary Ware <zachary.ware at gmail.com>:

A couple months ago, I had never before heard of function annotations and came across a function that had them (I don't remember where or what it was).  I spent a fair bit of time searching fruitlessly to figure out what the heck that "->" in the function definition meant.  Then finally, a week or two ago, I came across a mention of pep 3107 and function annotations, and figured out what it was that confused me so thoroughly.

In an effort to save others from the same confusion, I've put together a small subsection to add to the tutorial about function definition.  The text I'm proposing to add is as follows:

"""
:ref:`Function annotations <function>` are completely optional,
arbitrary metadata information about user-defined functions.  Python itself
currently does not use annotations for anything, so this section is just for
familiarity with the syntax.

Annotations are stored in the :attr:`__annotations__` attribute of the function
as a dictionary and have no effect on any other part of the function.  Parameter
annotations are defined by a colon after the parameter name, followed by an
expression evaluating to the value of the annotation.  Return annotations are
defined by a literal ``->``, followed by an expression, between the parameter
list and the colon denoting the end of the :keyword:`def` statement.  The
following example has a positional argument, a keyword argument, and the return
value annotated with nonsense::

   >>> def f(ham: 42, eggs: int = 'spam') -> "Nothing to see here":
   ...     print("Annotations:", f.__annotations__) # print the function's own annotations
   ...     print("Arguments:", ham, eggs)
   ...
   >>> f('wonderful')
   Annotations: {'eggs': <class 'int'>, 'return': 'Nothing to see here', 'ham': 42}
   Arguments: wonderful spam
"""

I'd also like to see a link for "->" in the index, either to this note or to the relevant paragraph of compound_stmts.rst or both.  The attached patch attempts to add such a link to this section, but I'm not certain that it's done properly.

Thanks :)

----------
assignee: docs at python
components: Documentation
files: annotations_tutorial.patch
keywords: patch
messages: 161451
nosy: docs at python, zach.ware
priority: normal
severity: normal
status: open
title: Tutorial: Add function annotation example to function tutorial
type: enhancement
versions: Python 3.2, Python 3.3
Added file: http://bugs.python.org/file25684/annotations_tutorial.patch

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue14893>
_______________________________________


More information about the New-bugs-announce mailing list