Decorators
Concepts covered: Decorators
A decorator is a function that takes a function and returns a function. Writing @log_calls on the line above def rank means rank = log_calls(rank), run right after the def. The name rank now points at whatever log_calls returned, and the original survives only if that returned function holds on to it.
def rank(likes):
return likes // 100
rank = log_calls(rank)
@log_calls
def rank(likes):
return likes // 100Writing a decorator
The returned function is usually a closure called wrapper. It accepts *args and **kwargs so it can stand in for a function of any signature, does its extra work, calls the original through the closure variable, and returns the original's result.
def log_calls(func):
def wrapper(*args, **kwargs):
print("calling", func.__name__, args)
result = func(*args, **kwargs)
print("returned", result)
return result
return wrapper
@log_calls
def rank(likes):
return likes // 100
score = rank(1205)
print("score is", score)
calling rank (1205,) returned 12 score is 12
While rank runs, the stage holds 2 frames: wrapper outside, rank inside. The caller asked for rank and got wrapper, which reached the original through func.
Keeping the original's name with functools.wraps
import functools
def plain(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def careful(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@plain
def rank(likes):
"""Bucket a like count into hundreds."""
return likes // 100
@careful
def tier(likes):
"""Label a post by its like count."""
return "viral" if likes > 1000 else "normal"
print(rank.__name__, rank.__doc__)
print(tier.__name__, tier.__doc__)Output:
wrapper None tier Label a post by its like count.
Without help, every decorated function reports itself as wrapper in tracebacks, logs and help(). functools.wraps(func) copies __name__, __doc__ and the other identifying attributes from func onto wrapper, and stores the original as wrapper.__wrapped__. It is itself a decorator, applied to the inner function, so it costs a single line.
Decorators that take arguments
@retry(times=3) contains a call. Python evaluates retry(times=3) first, and whatever that returns is the decorator. A configurable decorator is therefore 3 nested functions: the outer takes the settings, the middle takes the function, and the inner runs on every call.
import functools
def retry(times):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return func(*args, **kwargs)
except ConnectionError:
print("attempt", attempt, "failed")
raise ConnectionError(f"gave up after {times} attempts")
return wrapper
return decorator
failures = [True, True, False]
@retry(times=3)
def fetch_likes(post):
if failures.pop(0):
raise ConnectionError("timeout")
return {"post": post, "likes": 1205}
print(fetch_likes("p2"))Output:
attempt 1 failed
attempt 2 failed
{'post': 'p2', 'likes': 1205}The failures list stands in for a flaky network so the run repeats exactly: the first 2 calls raise and the third returns. @dataclass(frozen=True) from the previous section has this shape too: dataclass(frozen=True) returns a decorator, which receives the class and returns it with the generated methods attached.
Stacking decorators
Decorators stack, and the one nearest def is applied first: @a above @b above def f means f = a(b(f)). At call time a's wrapper starts first and calls b's wrapper, which calls f, and the result comes back out through b and then a.
What does this program print?
def double(func):
def wrapper(text):
return func(text) * 2
return wrapper
def exclaim(func):
def wrapper(text):
return func(text) + "!"
return wrapper
@double
@exclaim
def tag(name):
return name
print(tag("ana"))- ana!ana!
- anaana!
- ana!
- anaana
Caching with functools.lru_cache
functools.lru_cache is the memoization dict from the functions lessons, packaged as a decorator: it stores each result under the call's arguments and returns the stored value when the same arguments come back. It needs hashable arguments and assumes a pure function, which frozen records and pure steps provide.
import functools
calls = []
@functools.lru_cache(maxsize=None)
def account_age_days(user):
calls.append(user)
return {"ana": 1, "bo": 400, "cy": 0}[user]
for user in ["ana", "bo", "ana", "cy", "ana"]:
account_age_days(user)
print(calls)
print(account_age_days.cache_info())Output:
['ana', 'bo', 'cy'] CacheInfo(hits=2, misses=3, maxsize=None, currsize=3)
The calls list shows which calls ran the body: 3 of the 5 did, and the other 2 came from the cache. In real code that side effect would be a bug, since a cache hit skips it.
About this lesson
This section is part of the Functional Programming: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.