Improve Your Python Code With Type Hinting

Pavle Djuric
6 min readDec 30, 2021

One of Python’s main drawbacks is the fact that it is not statically typed, meaning you do not have to define the type of the variable you are declaring. For simple scripts it isn’t such a significant problem, but for enterprise applications that have huge teams and hundreds of thousands (or even millions) of lines of code, this can be a huge productivity issue.

Python’s initial resolution to this issue was the docstring which is basically a large comment block right under the function (or method) signature that should ideally describe each argument’s purpose, their types and the return type.

But, that pretty much defeats the whole “self-documenting code” principle. So, another solution was implemented, that is in my opinion much better- the typing module. It’s been a part of the standard library since version 3.5 and has been gaining traction ever since. In this article I will explain the basic use cases of the typing module in a few code examples.

Let’s start with the most basic example, a function that accepts two integers and returns their sum. The “traditional” way to write this in Python would be:

def add_two_nums(a, b):    return a+b

Since this is the simplest possible function you can write, there really isn’t too much that would confuse even the most junior of developers. But, let’s look at what this function would look like with type hints:

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

Pretty self explanatory I would say. The colons after the argument define their types, and the argument after the arrow defines the return type.

Okay, that was just to get our feet wet. Now let’s imagine a function that will take a dictionary as a parameter and return a list of the dictionary keys, but only the ones that are numerical. If there are no numerical keys, the function will return None.

Something like this:

def get_numerical_keys(elements):
numerical_keys = []
for key in elements.keys():
if isinstance(key, int):
numerical_keys.append(key)
if len(numerical_keys) > 0:
return numerical_keys
Pavle Djuric

Software developer. 3 x AWS certified. Writing mostly about Python, Golang, backend development and Cloud computing.

Lists

See more recommendations