Rodrigo Girão Serrão: Functions: a complete reference | Pydon't 🐍
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:
- How to structure and organise functions.
- How to work with a function signature, includingparameter order,
*argsand**kwargs, andthe special syntax introduced by*and/. - What anonymous functions are, how to define them with the keyword
lambda, andwhen to use them. - What it means for functions to be objectsand how to leverage that in your code.
- How closures seem to defy a fundamental rule of scoping in Python.
- How to leverage closures to create the decorator pattern.
- What the keyword
yieldis and what generator functions are. - What the keyword
asyncis and what asynchronous functions are. - How partial function application allows you to create new functions from existing functions.
- How the term “function” is overloadedand how you cancreate your own objects that behave like functions.
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