What do the colons in the following Python code do?

Question:

This code is from the python tutorial documents – 4.7.7. Function Annotations:

def f(ham: 42, eggs: int = 'spam') -> "Nothing to see here":
     print("Annotations:", f.__annotations__)
     print("Arguments:", ham, eggs)

I don’t know what the colons (:) after “ham” and “eggs” do. Please explain to me.

Asked By: ttriet204

||

Answers:

It’s basically a way to add arbitrary metadata to function arguments and/or return values. –Lukas Graf

It’s literally just a way to attach objects to functions, arguments and other stuff. You could use it for documentation, validation, or just to add meaningless data. –poke

Also see: PEP-3107

From the documentation directly:

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 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
Answered By: jgritty
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.