Annotation
In Python, annotations provide a way to attach metadata to function arguments and return values. You can use annotations for various purposes, such as type hinting, documentation, or even custom processing by decorators or frameworks.
While Python doesn’t enforce these annotations, they serve as valuable hints for developers and tools like linters, code editors, and integrated development environments (IDE) to understand the intended use of a function’s parameters and return value.
To add annotations, you use a colon (:
) followed by an expression after the parameter name and the return type is annotated with an arrow (->
) followed by an expression after the parameter list. These expressions can be any valid Python expressions but are typically used to specify data types.
Example
Here’s an example demonstrating how to use annotations in a Python 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 has a first parameter text
that is expected to be a string (str
). Then, it has an align
parameter that should be a Boolean value. The function return values should be a string.
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: