Member-only story
Python decorators provide an easy yet powerful way to modify functions and methods. Though the syntax may seem unusual at first, decorators allow you to encapsulate common bits of code you find yourself repeating. Once you learn to recognize these situations, decorators will clean up your code considerably.
Understanding Python Decorators through Examples
The basic motivation behind decorators is the DRY principle — Don’t Repeat Yourself. For example, let’s say you have this simple function:
def add_tax(price):
return price * 1.09
You want to log every time add_tax()
gets called. Without decorators, you would have to edit the function itself:
def add_tax(price):
print(“Calling add_tax()”)
return price * 1.09
This works, but gets messy if you want to add logging to many functions in your code. Instead, we can define a decorator called `log_calls` that handles this for us:
def log_calls(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}()")
return func(*args, **kwargs)
return wrapper
@log_calls
def add_tax(price):
return price * 1.09