Image

Rodrigo Girão Serrão: Functions: a complete reference | Pydon't 🐍

Image

This article serves as a complete reference for all the non-trivial things you should know about Python functions.

Functions are the basic building block of any Python program you write, and yet, many developers don't leverage their full potential. You will fix that by reading this article.

Knowing how to use the keyworddefis just the first step towards knowing how to define and use functions in Python. As such, this Pydon't covers everything else there is to learn:

What goes into a function and what doesn't

Do not overcrowd your functions with logic for four or five different things. A function should do a single thing, and it should do it well, and the name of the function should clearly tell you what your function does.

If you are unsure about whether some piece of code should be a single function or multiple functions, it's best to err on the side of too many functions. That is because a function is a modular piece of code, and the smaller your functions are, the easier it is to compose them together to create more complex behaviours.

Consider the functionprocess_orderdefined below, an exaggerated example that breaks these best practices to make the point clearer. While it is not incredibly long, it does too many things:

def process_order(order): # Validate the order: for item, quantity, price in order: if quantity <= 0: raise ValueError(f"Cannot buy 0 or less of {item}.") if price <= 0: raise ValueError(f"Price must be positive.") # Write the receipt: total = 0 with open("receipt.txt", "w") as f: for item, quantity, price in order: # This week, yoghurts and batteries are on sale. if "yoghurt" in item: price *= 0.8 elif "batteries" in item: price *= 0.5 # Write this line of the receipt: partial = price * quantity f.write(f"{item:>15} --- {quantity:>3}...

https://mathspp.com/blog/pydonts/functions-a-complete-reference