changeset: 80166:45167091b5f9 branch: 3.3 parent: 80162:717660ec8f67 parent: 80165:2bf99322218f user: Andrew Svetlov date: Thu Nov 01 21:27:23 2012 +0200 description: Merge issue #14893: Add function annotation example to function tutorial. Patch by Zachary Ware. diff -r 717660ec8f67 -r 45167091b5f9 Doc/tutorial/controlflow.rst --- a/Doc/tutorial/controlflow.rst Thu Nov 01 20:15:23 2012 +0100 +++ b/Doc/tutorial/controlflow.rst Thu Nov 01 21:27:23 2012 +0200 @@ -656,6 +656,40 @@ No, really, it doesn't do anything. +.. _tut-annotations: + +Function Annotations +-------------------- + +.. sectionauthor:: Zachary Ware +.. index:: + pair: function; annotations + single: -> (return annotation assignment) + +:ref:`Function annotations ` 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': , 'return': 'Nothing to see here', 'ham': 42} + Arguments: wonderful spam + + .. _tut-codingstyle: Intermezzo: Coding Style

AltStyle によって変換されたページ (->オリジナル) /