diff options
author | Andrew Svetlov <andrew.svetlov@gmail.com> | 2012-11-01 19:27:23 (GMT) |
---|---|---|
committer | Andrew Svetlov <andrew.svetlov@gmail.com> | 2012-11-01 19:27:23 (GMT) |
commit | 7c91dbec0ed16b2dba8ce5d923015e821333b673 (patch) | |
tree | d642ed41b51d898e9d9dff60ba4f6bc71921e165 /Doc/tutorial | |
parent | 0168d3d9b1f6c236b23afedab3c61254fcb6f072 (diff) | |
parent | 1491cbdf6374fc47f89476e3fbd1acfbc4de5ea9 (diff) | |
download | cpython-7c91dbec0ed16b2dba8ce5d923015e821333b673.zip cpython-7c91dbec0ed16b2dba8ce5d923015e821333b673.tar.gz cpython-7c91dbec0ed16b2dba8ce5d923015e821333b673.tar.bz2 |
Merge issue #14893: Add function annotation example to function tutorial.
Patch by Zachary Ware.
Diffstat (limited to 'Doc/tutorial')
-rw-r--r-- | Doc/tutorial/controlflow.rst | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/Doc/tutorial/controlflow.rst b/Doc/tutorial/controlflow.rst index 574f0d0..055f547 100644 --- a/Doc/tutorial/controlflow.rst +++ b/Doc/tutorial/controlflow.rst @@ -656,6 +656,40 @@ Here is an example of a multi-line docstring:: No, really, it doesn't do anything. +.. _tut-annotations: + +Function Annotations +-------------------- + +.. sectionauthor:: Zachary Ware <zachary.ware@gmail.com> +.. index:: + pair: function; annotations + single: -> (return annotation assignment) + +:ref:`Function annotations <function>` are completely optional, +arbitrary metadata information about user-defined functions. Neither Python +itself nor the standard library use function annotations in any way; this +section just shows the syntax. Third-party projects are free to use function +annotations for documentation, type checking, and other uses. + +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("Arguments:", ham, eggs) + ... + >>> f('wonderful') + Annotations: {'eggs': <class 'int'>, 'return': 'Nothing to see here', 'ham': 42} + Arguments: wonderful spam + + .. _tut-codingstyle: Intermezzo: Coding Style |