Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1491cbd

Browse files
committed
Issue #14893: Add function annotation example to function tutorial.
Patch by Zachary Ware.
1 parent e4ad37e commit 1491cbd

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

Doc/tutorial/controlflow.rst

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -656,6 +656,40 @@ Here is an example of a multi-line docstring::
656656
No, really, it doesn't do anything.
657657

658658

659+
.. _tut-annotations:
660+
661+
Function Annotations
662+
--------------------
663+
664+
.. sectionauthor:: Zachary Ware <[email protected]>
665+
.. index::
666+
pair: function; annotations
667+
single: -> (return annotation assignment)
668+
669+
:ref:`Function annotations <function>` are completely optional,
670+
arbitrary metadata information about user-defined functions. Neither Python
671+
itself nor the standard library use function annotations in any way; this
672+
section just shows the syntax. Third-party projects are free to use function
673+
annotations for documentation, type checking, and other uses.
674+
675+
Annotations are stored in the :attr:`__annotations__` attribute of the function
676+
as a dictionary and have no effect on any other part of the function. Parameter
677+
annotations are defined by a colon after the parameter name, followed by an
678+
expression evaluating to the value of the annotation. Return annotations are
679+
defined by a literal ``->``, followed by an expression, between the parameter
680+
list and the colon denoting the end of the :keyword:`def` statement. The
681+
following example has a positional argument, a keyword argument, and the return
682+
value annotated with nonsense::
683+
684+
>>> def f(ham: 42, eggs: int = 'spam') -> "Nothing to see here":
685+
... print("Annotations:", f.__annotations__)
686+
... print("Arguments:", ham, eggs)
687+
...
688+
>>> f('wonderful')
689+
Annotations: {'eggs': <class 'int'>, 'return': 'Nothing to see here', 'ham': 42}
690+
Arguments: wonderful spam
691+
692+
659693
.. _tut-codingstyle:
660694

661695
Intermezzo: Coding Style

0 commit comments

Comments
 (0)