Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Variable Annotation | Annotations
Mastering Python: Annotations, Errors and Environment
course content

Contenido del Curso

Mastering Python: Annotations, Errors and Environment

Mastering Python: Annotations, Errors and Environment

1. Annotations
2. Function Arguments in Details
3. Error Handling
4. Virtual Environment

bookVariable Annotation

Let's create a type annotation for a variable.

To annotate a variable with a type, you need to use a colon (:) followed by the data type after the variable:

Annotations are meant for the benefit of programmers and do not affect the ability to assign a value of a certain data type to the annotated variable:

123
number: int = "TheBestString" print(number)
copy

The IDE (Integrated Development Environment) will flag an error if you assign a value of a different type than the one annotated.

Let's take a look at an example in PyCharm:

In the above example, PyCharm alerts us that we are assigning a value of an unexpected data type to the number variable.

Multiple Type Annotations In Python, you can annotate a variable with multiple types using the | symbol (available since Python 3.10):

In the above example, PyCharm assigns the float value (12.24) to the number variable without any issues.

If you are using Python 3.9 or an earlier version, you can use the imported Union object from the typing module to annotate multiple types:

Nested Annotations

A list data structure can contain values of different types. In cases where you need a list containing only int or float values, nested annotations can be used:

The syntax list[int] has been available since Python 3.9. If you are using an earlier version of Python, you can import the List object from the typing module:

Similarly, these annotations can be used for set data structures.

Annotations can also be created for dict data structures, where the first position represents the annotation for keys, and the second position represents the annotation for values:

Note

The types inside dict[] and Dict[] are separated by commas (,).

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 1. Capítulo 2
We're sorry to hear that something went wrong. What happened?
some-alt