- La funzione 'add_all' è un esempio di come si possono gestire input e output di tipo imprevedibile
- La struttura della funzione richiede un'analisi approfondita per comprendere il comportamento
Member-only story
Write Python Functions Like This Or I’ll Reject Your Pull Request
This was the energy I was getting from my tech lead at work. And I actually agree with him at this point.
How we were taught to write Python functions
Here’s a simple function that takes in:
- a list of numbers
num_list
- a number
num
- adds
num
to every single number innum_list
- and returns a new list
def add_all(num_list, num):
output = []
for n in num_list:
output.append(n + num)
return output
x = add_all([3, 4, 5], 10)
print(x) # 13, 14, 15
Problem — we don’t know at first glance:
- what data types this function takes in
- what data type this function returns
I mean, we can infer from reading the code that num_list
is a list of numbers, num
is a number, and that the function returns a list of numbers. But this isn’t instant.
And in a larger production-grade app, we have thousands of functions to deal with. Do we really want to spend this extra time figuring out and inferring data types?