
Code
Caches, Registries & Class Decorators
Decorators shine for cross-cutting jobs, things many functions need but that aren't their main purpose:
import functools, time
def timed(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return func(*args, **kwargs)
finally:
ms = (time.perf_counter() - start) * 1000
print(f"{func.__name__} took {ms:.2f} ms")
return wrapper
- Caching: remember results for arguments seen before. The standard
library has this built in as
@functools.cacheand@functools.lru_cache(maxsize=128): but building one teaches a lot. - Registries: a decorator can simply record a function somewhere
and return it unchanged. Web frameworks use this for routes
(
@app.get("/home")). - Class decorators: the same idea applied to a class. Receive the
class, modify or register it, return it.
@dataclassis one!
Assignment
memoize(func): finish the wrapper so it returnscache[args]whenargswas seen before, otherwise callsfunc, stores the result incache, and returns it.command(name): a decorator factory that stores the decorated function inCOMMANDS[name]and returns the function unchanged.with_repr(cls): a class decorator that givesclsa__repr__showingClassName(attr=value, ...)built fromvars(self), values shown withrepr. Returncls.
memoize(func): finish the wrapper so it returnscache[args]whenargswas seen before, otherwise callsfunc, stores the result incache, and returns it.command(name): a decorator factory that stores the decorated function inCOMMANDS[name]and returns the function unchanged.with_repr(cls): a class decorator that givesclsa__repr__showingClassName(attr=value, ...)built fromvars(self), values shown withrepr. Returncls.
main.py Python sleeping
Press Run to try your code, then Check to test it.