Function Annotation

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

These annotations are stored in the function’s .__annotations__ attribute and can be any valid Python expression, typically a data type or a string describing the expected data type.

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:

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 arguments. The text argument should be a string while the align argument should be a Boolean value. The function should return a string.

The annotations are available through the .__annotations__ attribute:

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

The .__annotations__ holds a dictionary mapping attribute names to expected data types.

Tutorial

Python Type Checking (Guide)

In this guide, you'll look at Python type checking. Traditionally, types have been handled by the Python interpreter in a flexible but implicit way. Recent versions of Python allow you to specify explicit type hints that can be used by different tools to help you develop your code more efficiently.

intermediate best-practices

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


By Leodanis Pozo Ramos • Updated Dec. 19, 2024 • Reviewed by Dan Bader