That is the strategy we adopted at work, and I’m absolutely on board with it.
The Manner We Had been Taught to Write Python Capabilities
Right here’s a primary perform:
- It takes in an inventory of numbers
num_list
and a quantitynum
- It provides
num
to every component innum_list
- It returns a brand new record
def add_all(num_list, num):
output = []
for n in num_list:
output.append(n + num)
return outputx = add_all([3, 4, 5], 10)
print(x) # Output: [13, 14, 15]
The Downside
At first look, this perform doesn’t inform us:
- What knowledge varieties it accepts.
- What knowledge kind it returns.
Certain, after studying the code, we are able to guess that num_list
is an inventory of numbers, and num
is a quantity, nevertheless it’s not instantly clear. In a production-grade app with hundreds of capabilities, losing time on such guesses provides up.
Sort Annotations to the Rescue
That is the place kind annotations (additionally referred to as kind hints) turn out to be useful. Let’s enhance the perform by including them.