Lesson 4 of 5 · Advanced Python · 3 min read · Updated
Decorators
Wrapping a function to add behaviour around it, without changing its code.
A decorator is a function that takes a function and returns a new one that wraps it — doing something before, after, or instead. It is a closure put to work.
def shout(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper() + "!"
return wrapper
@shout
def greet(name):
return f"hello {name}"
print(greet("kavya"))
HELLO KAVYA!
Example
@shout above def greet is exactly greet = shout(greet) written after it. The name greet now points to the wrapper, which calls the original and changes its result.
A useful decorator
import functools
def count_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
wrapper.calls += 1
return func(*args, **kwargs)
wrapper.calls = 0
return wrapper
@count_calls
def add(a, b):
return a + b
add(1, 2)
add(3, 4)
print(add.calls, add.__name__)
2 add
*args, **kwargs let the wrapper accept whatever the original accepts. @functools.wraps(func) copies the original's name and docstring onto the wrapper — without it, add.__name__ would say "wrapper".
Decorators that take arguments
import functools
def repeat(times):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for _ in range(times):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def cheer():
print("Go!")
cheer()
Go!
Go!
Go!
Note
@repeat(3) first calls repeat(3), which returns the real decorator. That is why it has three levels of function. You have already used decorators that come with Python: @property, @classmethod, @staticmethod.
@log is written above def save():. What is that the same as?
Try this now
- Write a
@logdecorator that prints the function name and its arguments before each call. - Write a
@timerdecorator usingtime.perf_counter()that prints how long a function took.
Create a free account to save your progress, or sign in.