
Code
Your First Decorator
Functions are objects: you can pass them around and return them. A decorator is a function that takes a function and returns a new one that usually calls the original with something extra around it.
def announce(func):
def wrapper(*args, **kwargs):
print("Casting", func.__name__)
return func(*args, **kwargs)
return wrapper
@announce # same as: spark = announce(spark)
def spark(colour):
return f"a {colour} spark"
spark("blue") # prints "Casting spark", returns 'a blue spark'
Three habits make wrappers safe:
- accept
*args, **kwargsso any arguments pass straight through; - return the original function's result;
- return
wrapperitself (notwrapper()!) from the decorator.
A wrapper is a function object, so you can even hang attributes on it:
wrapper.calls = 0.
Assignment
shout(func): a decorator whose wrapper callsfuncand returns the result upper-cased.count_calls(func): a decorator whose wrapper has an attributecallsthat starts at0and goes up by one every time the decorated function is called. It must still returnfunc's result.
shout(func): a decorator whose wrapper callsfuncand returns the result upper-cased.count_calls(func): a decorator whose wrapper has an attributecallsthat starts at0and goes up by one every time the decorated function is called. It must still returnfunc's result.
main.py Python sleeping
Press Run to try your code, then Check to test it.