Variable Annotation

In Python, variable annotation allows you to attach type hints to variables. This feature was introduced in Python 3.6 lets you indicate the expected data type of a variable.

These annotations improve code readability and assist with static type checkers like mypy. However, it’s important to note that variable annotations don’t enforce type constraints at runtime. They’re purely informational.

You can use variable annotations by placing a colon (:) followed by the type after the variable name. This can be particularly useful in documenting your code and making it more understandable for other developers.

Example

Here’s a quick example of how you might use variable annotations in Python:

Python
>>> fruits: list[str] = []

>>> fruits.append("apple")
>>> fruits.append("orange")

In this example, the fruits variable holds an empty list, which must contain string objects. You know this because of the type hint you provided through the variable annotation. Later, when you use the variable, you must ensure that the added values have the correct data type.

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