Type Hints in Python: A Guide to Better Code

Type Hints makes code self explanatory!

Type Hints in Python: A Guide to Better Code

Photo by Riku Lu on Unsplash

What is Type Hints?

Type Hint is literally what the word mean. you get hint of the data type of functions input & output, type hints helps understanding and debugging the code. in standard way of shipping code using Type Hints can add significant value.

Why to use Type Hints?

Python is a dynamically typed language, which means you never have to explicitly indicate what kind of types variable has.

But in some cases, dynamic typing can lead to some bugs that are very difficult to debug and in those cases, Type Hints or Static Typing can be convenient.

Type hints help document your code. Traditionally, you would use docstrings if you wanted to document the expected types of a function’s arguments. This works for now as well but as there is no standard for docstrings, they can’t be easily used for automatic checks.

You need to consider using type hints to help others and yourself. Type hints increase the readability with self-explanatory code.

Type hints also help you to build and maintain a cleaner code architecture as you need to consider types when annotating them in your code.

Type Hints has been introduced as a new feature in Python 3.5.

Standard way of writing Type Hints

let's look at following function as an example

# function without Type Hints
def addition(a, b):
    return a + b
print(addition(3, 5)) # 8

**Here’s how to add type hints to the above function: **

  1. Add a colon and a data type after each function parameter

  2. Add an arrow (->) and a data type after the function to specify the return data type

Code-wise, it looks more like this:

# functions with Type Hints
def addition(a: int, b: int) -> int:
    return a + b
print(addition(3, 5)) # 8

The typing Module

Python’s typing module can make data type annotations even more verbose. For example, you can specifically declare a list of strings, a tuple containing three integers, and a dictionary with strings as keys and integers as values.

Here’s how:

from typing import List, Tuple, Dict

my_list: List[str] = ['a', 'b', 'c']
my_tuple: Tuple[int, int, int] = (1, 2, 3)
my_dictionary: Dict[str, int] = {'a': 1, 'b': 2}

Automatically add Type Hints

let's go to fun part now, let's say you have lot of functions in your python file and you want to add Type Hints for all of them... then a library called MonkeyType can help.

let's see how to use it.

for installation:

pip install MonkeyType

for simplicity, I'm using simple functions you can follow the same process on your own files

here's mango_without_typehints.py file contains all the functions I'm using (it's mango season here so I named it as mango😁)

mango_without_typehints.png

and test.py is a file where I'm calling those functions

test_functions.png

open your preferred command prompt and activate your working environment if any, and navigate to the particular directory where your files are present and run following command:

monkeytype run test.py

after that you'll get somewhat like this output, so in the backend it will create dump call traces into a SQLite database in the file monkeytype.sqlite3

conda_run_test_file.png

Then, you'll apply those traces to your mango_without_typehints.py file where your functions are defined, make sure pass that file without extension

monkeytype apply mango_without_typehints

you'll get somewhat like this output

monkeytype_apply.png

Now, go check your mango_without_typehints.py file, type hints will be updated there for each functions

final_file_with_typehintspng.png

Here's the files for you to download and try which are being used here Download via GitHub

Until next time, chill, relax and keep learning!

Did you find this article valuable?

Support Shreyas' Blog by becoming a sponsor. Any amount is appreciated!