Python Type Hints: Your Secret Weapon for Readable and Reliable Code — Part 1

Marco Franzon
4 min readMar 2, 2023

--

Python is a dynamically typed language, which means that the type of a variable can change during runtime. This can lead to some unexpected behaviors and bugs in the code. However, with the introduction of type hints in Python 3.5, developers can now provide hints about the expected types of their code. In this article, I will discuss the importance of Python type hints and how they can make our code more readable and reliable.

Type hints in Python are annotations that allow developers to specify the type of a variable, function parameter, or return value. The syntax for a type hint is to use a colon followed by the expected type. For example, if I have a function that takes an integer parameter, I can specify the type hint like this:

def add_numbers(a: int, b: int) -> int:
return a + b

In this example, I have specified that both a and b should be integers and that the function should return an integer.

One of the main benefits of using type hints is that they make the code more readable and self-documenting. When someone reads the code, they can quickly see what types of variables are expected and what the function should return. This can make it easier to understand how the code works and can also make it easier to catch bugs.

Consider now a more complex case, in which a function requires a custom type:

from dataclasses import dataclass

@dataclass
class MyType():
x: int
y: int

@property
def sum_x_y(self) -> int:
return self.x + self.y

def foo(first: int, second: int ) -> MyType:
_new = MyType(first, second)
return _new

In this example I defined a new class called MyType and then I use it inside the function foo.In this case, I simply suggest that return type of the function is our declared class.

Type Aliasing and more Complex Types

Another benefit of using type hints is that they can help with code maintenance. As code-bases grow larger and more complex, it can be difficult to remember what types of variables a function expects or what it should return. By using type hints, developers can easily see this information without having to dig through the code or documentation.

For this reason you can use or encounter complex types, which are a combination of two or more types. With the same logic, you can rename that new complex type into a new type with an alias, in order to keep code more readable.

from typing import Dict
from typing import List
from typing import Union


TupleAlias = Tuple[str, int]
ComplexUnion = Union[str, TupleAlias]
ComplexMapping = Dict[str, List[ComplexUnion]]

In the previous example, there are used more complex types and then combined together to create new types. I use the aliasing to make the code more readable without having long-nested type definitions. Thanks to aliasing you can be extremely clear in what represents the type, using a proper alias name.

Protocols, the most advanced typing

The typing module defines various protocol classes that correspond to common Python protocols, such as Iterable[T]. In this specific case, If a class defines a suitable __iter__ method, mypy understands that it implements the iterable protocol and it is compatible with Iterable[T] .

You can define your own protocol class by inheriting the special Protocol class:

from typing_extensions import Protocol

class SupportsClose(Protocol):
# Empty method body (explicit '...')
def close(self) -> None: ...

class Resource: # No SupportsClose base class!

def close(self) -> None:
self.resource.release()

# ... other methods ...

In this example a new protocol SupportsClose is defined. This means that any other class that defines a compatible close method will be a subtype of the custom protocol, like List or Dict are subtypes of the Iterable[T] protocol. In this case,Resource is a subtype of the SupportsClose protocol since it defines a compatible close method.

In conclusion, type hints are an important tool for Python developers. They make the code more readable, reliable, and easier to maintain. By using type hints, developers can catch bugs earlier and save time in debugging. So if you’re not already using type hints in your Python code, it’s time to start!

--

--