Programming Search⌘K

Featurecore

Function annotations

Also called parameter annotation, return annotation, arrow in def, __annotations__, type hints on functions, PEP 3107, annotate a function.

A parameter can have an annotation after a colon, and a function can have a return annotation after ->. Python stores them in __annotations__ and does not check them. Type checkers read them.

Language
Python

Synopsis

def f(ham: str, eggs: str = "eggs") -> str:
    return ham + " and " + eggs

print(f("spam"))
print(f.__annotations__["ham"], f.__annotations__["return"])
Output
spam and eggs
<class 'str'> <class 'str'>

ham: str annotates a parameter, and -> str annotates the return value. The annotations are in the dict f.__annotations__.

Semantics

r1. "Function annotations are completely optional metadata information about the types used by user-defined functions".1

r2. "Annotations are stored in the annotations attribute of the function as a dictionary and have no effect on any other part of the function."1 Example: not-checked.

r3. "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."1

r4. "Any parameter may have an annotation, even those of the form *identifier or **identifier."2 Example: star.

r5. "Annotations are conventionally used for type hints, but this is not enforced by the language, and in general annotations may contain arbitrary expressions."2 Example: any-expression.

r6. PEP 3107 says: "By itself, Python does not attach any particular meaning or significance to annotations."3

r7. The reference says: "By default, annotations are lazily evaluated in an annotation scope. This means that they are not evaluated when the code containing the annotation is evaluated."2 So do not write code that depends on the time when Python evaluates an annotation.

Examples

def double(x: int) -> int:
    return x * 2

print(double("ab"))
Output
abab

The annotation says int, but Python does not check it (rule r2).

def log(*messages: str, **options: bool) -> None:
    print(" ".join(messages), options)

log("a", "b", verbose=True)
print(sorted(log.__annotations__))
Output
a b {'verbose': True}
['messages', 'options', 'return']
def move(distance: "metres", speed: "metres per second") -> "seconds":
    return distance / speed

print(move(100, 4))
print(move.__annotations__["speed"])
Output
25.0
metres per second

An annotation can be any expression, such as a string (rule r5).

Pitfalls

A lambda cannot have annotations. The reference says that "functions created with lambda expressions cannot contain statements or annotations."5

This code raises SyntaxError, on purpose.

f = lambda x: int: x

A default comes after the annotation: write eggs: str = "eggs", not eggs = "eggs": str.

Comparison

In Go, the type of each parameter is part of the function type: "A function type denotes the set of all functions with the same parameter and result types."4 Go checks that "arguments must be single-valued expressions assignable to the parameter types of F".4 A Python annotation is metadata, and Python does not check a call against it (rule r6).

References

  1. The Python Tutorial, 4. More Control Flow Tools, 4.9.8. Function Annotations
  2. The Python Language Reference, Python 3.15, 8.11. Annotations; 8.7. Function definitions
  3. PEP 3107: Function Annotations, Fundamentals of Function Annotations
  4. The Go Programming Language Specification, Function types; Calls
  5. The Python Language Reference, Python 3.15, 6.14. Lambdas

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source