Skip to content

function annotation

In Python, function annotation is a way to attach type information or type hints to function parameters and return values.

These annotations are available through the function’s .__annotations__ attribute and can be any valid Python expression, typically a data type, or in older code a string naming a type that isn’t defined yet.

Since Python 3.14, annotations are evaluated lazily, as specified in PEP 649 and PEP 749. Python stores them in a special annotate function on the function’s .__annotate__ attribute and only evaluates them when something actually reads .__annotations__. That also means string-quoting a forward reference is no longer necessary.

Function annotations don’t force Python to perform type checking at runtime. Instead, they serve as documentation and can be used by static type checkers and other tools to provide useful information for debugging purposes. This makes annotations a powerful tool for improving code readability and maintainability.

Example

Here’s an example of how to use function annotations to provide type hints for a function:

Language: Python
>>> def headline(text: str, align: bool = True) -> str:
...     if align:
...         return f"{text.title()}\n{'-' * len(text)}"
...     else:
...         return f" {text.title()} ".center(50, "o")
...

In this example, the headline function takes two parameters. The text parameter should be a string while the align parameter should be a Boolean value. The function should return a string.

The annotations are available through the .__annotations__ attribute:

Language: Python
>>> headline.__annotations__
{'text': <class 'str'>, 'align': <class 'bool'>, 'return': <class 'str'>}

The .__annotations__ attribute holds a dictionary whose keys are the annotated parameter names, plus the special key 'return' for the return annotation, and whose values are the annotation objects themselves.

Since Python 3.14, the docs recommend retrieving annotations with annotationlib.get_annotations() rather than reading .__annotations__ directly, because the helper resolves forward references and other edge cases reliably:

Language: Python
>>> import annotationlib

>>> annotationlib.get_annotations(headline)
{'text': <class 'str'>, 'align': <class 'bool'>, 'return': <class 'str'>}
How to Use Type Hints for Multiple Return Types in Python

Tutorial

How to Use Type Hints for Multiple Return Types in Python

In this tutorial, you'll learn to specify multiple return types using type hints in Python. You'll cover working with one or several pieces of data, defining type aliases, and type checking with a third-party static type checker tool.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Aug. 22, 2026 • Reviewed by Dan Bader