Tips and Tricks
Why decorators in Python are pure genius
Analyze, test, and re-use your code with little more than an @ symbol
If there’s one thing that makes Python incredibly successful, that would be its readability. Everything else hinges on that: if code is unreadable, it’s hard to maintain. It’s also not beginner-friendly then — a novice getting boggled by unreadable code won’t attempt writing its own one day.
Python was already readable and beginner-friendly before decorators came around. But as the language started getting used for more and more things, Python developers felt the need for more and more features, without cluttering the landscape and making code unreadable.
Decorators are a prime-time example of a perfectly implemented feature. It does take a while to wrap your head around, but it’s worth it. As you start using them, you’ll notice how they don’t overcomplicate things and make your code neat and snazzy.
Before anything else: higher-order functions
In a nutshell, decorators are a neat way to handle higher-order functions. So let’s look at those first!
Functions returning functions
Say you have one function, greet()
— it greets whatever object you pass it. And let’s say you have another function, simon()
— it inserts “Simon” wherever appropriate. How can we combine the two? Think about it a minute before you look below.
def greet(name):
return f"Hello, {name}!"def simon(func):
return func("Simon")simon(greet)
The output is 'Hello, Simon!'
. Hope that makes sense to ya!
Of course we could have just called greet("Simon")
. However, the whole point is that we might want to put “Simon” into many different functions. And if we don’t use “Simon” but something more complicated, we can save a whole lot of…