Type Hints

Let’s begin with the following thought exercise. You have decided to create a a function that adds one to the input.

def add_one(x):
	return x + 1

Before making this nifty function publicly available for all to use, you decide to have your friend play around with the function to make sure that it works as you expect. Your friend writes and runs following lines of code only to realize the that third line creates a bug in Python:

add_one(2)
add_one(34.5)
add_one('Lebron') # You can’t add 1 to Lebron! 

Your initial idea is to create a distinct add_one function for each data type that you expect to work with the function**.** So far, we’ve seen several data types in Python: int, float, str, bool. So your idea is to create a function for integers and another one for floats (numbers with decimal point).

def add_one_int(x):
	return x + 1
	
def add_one_float(x):
	return x + 1 

Intuitively, though, this doesn’t strike you as a great idea. Both of the functions perform the same transformation. Writing code that is largely repetitive makes your code error prone. If you want to change something about the function, you would have to make the change for each distinct function.

Python provides us with something that can help us in this situation. Via type hints, we can specify both the type of the input that the user should call the function with as well as the type of output the user can expect the function to return. The | can be understood as “or”. So if our function can work across multiple data types (but not all!) we can use |. In the code block below, we specify that both the input and output types to the function can be either an int or a float.

def add_one(x: int | float) -> int | float:
	return x + 1 

Now it’s important to understand, that type hints won’t prevent a user from calling add_one('Lebron'), but now it won’t be our problem. We indicated the input & output types. If the user decides to ignore the types hints, there’s not much we can do.