We have the answers to your questions! - Don't miss our next open house about the data universe!

Typing and Annotation in Python: How does it work?

- Reading Time: 4 minutes
Typing and annotations in Python provide a way to add type hints to functions, variables, and other objects, without actually

When you're learning to code in Python, the question of typing is one that is rarely considered, whereas it's unavoidable with a language like Java. So where does this "oversight" on the part of one of the most widely used programming languages of the last decade come from?

To answer this question, it’s important to delve into a few basic concepts. Software development requires a clear understanding of data typing and how data is used in different contexts. Typing in programming defines the nature of the values that can be taken by the data we manipulate. To test the type of a variable in Python, we use the type() function, which, unsurprisingly, returns the type of the object entered as the function’s parameter.

The function is used as follows:

The type of argument is displayed using the print() function in the form:

>> <class ‘int’>

In the example above, we’re testing an integer numeric variable, the corresponding type is int. In Python, there are a multitude of so-called native types, you can find the exhaustive list on the official documentation. website. Python, being a dynamically typed language, is quite flexible when it comes to managing data types, but this flexibility can sometimes lead to confusion and errors. That’s where type annotations come in, adding an extra layer of clarity and type checking to Python code.

Typing in programming

There are two main types of typing in programming: static typing and dynamic typing.

1. Static typing

In a statically typed language, each variable must be assigned to a type specified by the programmer. Languages such as Java, C and C++ take this approach. Let’s take the example of Java for the definition of a numeric variable, the syntax is as follows:.

int a = 2;.

float b = 3.;

String c = ‘Hello World’;.

You don’t need a mastery of Java to understand this syntax. Each variable a, b or c is introduced by its type, followed by the assigned value.

The static aspect of typing is clearly apparent, and to verify this, simply see what would happen if you tried to assign a new value to one of the variables. You can try it yourself on this online compiler.

An important advantage of this approach is the rigor it imposes on variable definition: there’s no doubt about the nature of variables, and it becomes easier for the compiler to spot type-related errors. What’s more, type checking is generally performed at compile time, which means faster execution.

2. Dynamic typing

In contrast, Python opts for dynamic typing. This means that typing is performed and checked after code execution, not before. So, when you define a variable in Python, you don’t have to specify its type; it’s deduced by the interpreter. What’s more, once a variable has been defined, you can assign it a new value, whatever its type, without causing an error.

Example:

In conclusion, which typing should you choose? There’s no fixed answer to this question: it’s defined by the programming framework. If the mission demands absolute rigor and transparency in the code, then static typing is the way to go. If the programmer wants to have a free hand over the code, then the flexibility and writing speed of dynamic typing may be the right solution.

But if you want static typing, should you avoid Python?

Type annotations in Python

To simulate static typing, Python offers a system of type annotations. Type annotations allow the programmer to specify the type of a function’s arguments and the type of its return value. For example :

This function, which takes as argument a string a, worth by default ‘Hello World’ and which displays this string as output, allows us to specify two annotations:
  • The first annotation corresponds to the type of variable desired as argument, a: str. Here, we indicate that the argument a entered by the user of our function must be of type str.
  • The second annotation indicates the type of the output value of our function, -> None. Here, we indicate that the function returns nothing, which is consistent with its purpose of displaying only a result.
These annotations are accessed using the __annotations__ attribute, in the case of our example, we’ll have the following annotations:

It’s important to note that these annotations are indications, not strict constraints. Python does not prevent code execution if the actual types do not match the annotated types. However, these annotations can be very useful for understanding the programmer’s intention and detecting potential typing errors.

MyPy: a type checker for Python

While type annotations are useful, they don’t provide any real type checking in Python. To fill this gap, you can use third-party tools like MyPy.

MyPy is a Python library that checks the static typing of Python code and helps find bugs before your program runs. It works in conjunction with type annotations to ensure that they are respected. MyPy does not render code invalid if typing is not respected, but it does provide a detailed report of typing errors encountered. This allows the developer to correct these errors before they cause problems in code execution.

The most common way to use it is as a debugger according to the following scheme:

    1. Write your Python code and save it as a .py.

file.

  1. On a terminal, enter the following command: mypy my_file.py

If errors are detected, they will be returned by MyPy, specifying the type of error, its position in the code and the cause of the error.

In conclusion, although Python is a dynamically typed language, the use of type annotations and type checkers like MyPy can greatly improve the clarity and robustness of Python code. These tools can be particularly useful in large software development projects, where a clear understanding of data typing is essential to maintaining high-quality code.

You are not available?

Leave us your e-mail, so that we can send you your new articles when they are published!
icon newsletter

DataNews

Get monthly insider insights from experts directly in your mailbox