2014/01/22

Python 3.3 Function Annotations


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 __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 def statement. The following example has a positional argument, a keyword argument, and the return value annotated with nonsense:



def test(number:18, name: "test") -> "Test":
 print("Annotations:", test.__annotations__)
 print(number, name)

test("12345","Test value")



參考資料:
http://docs.python.org/3/tutorial/controlflow.html#function-annotations