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 (IDEs) to understand the intended use of a function’s parameters and return value.
To add annotations, place a colon (:
) and an expression after each parameter name. To annotate a return type, use an arrow (->)
and an expression after the parameter list. These expressions can be any valid Python expression, but they’re most often used to specify data types.
Example
Here’s an example of 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: