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:
>>> 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:
>>> headline.__annotations__
{
'text': <class 'str'>,
'align': <class 'bool'>,
'return': <class 'str'>
}
The .__annotations__
holds a dictionary mapping attribute names to expected data types.
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Defining Your Own Python Function (Tutorial)
- The Python return Statement: Usage and Best Practices (Tutorial)
- How to Use Type Hints for Multiple Return Types in Python (Tutorial)
- Python Type Checking (Course)
- Python Type Checking (Quiz)
- Defining and Calling Python Functions (Course)
- Defining Your Own Python Function (Quiz)
- Using the Python return Statement Effectively (Course)
- The Python return Statement (Quiz)
- Using Type Hints for Multiple Return Types in Python (Course)