functools.wraps copies __name__/__doc__/__module__ but the wrapper's ACTUAL call signature (as seen by inspect.signature()) is still `(*args, **kwargs)` unless you also explicitly copy or reconstruct the __wrapped__ attribute (which wraps() DOES set) — inspect.signature() automatically follows __wrapped__ to find the TRUE original signature.
Protect the shared cache dictionary with a threading.Lock inside the decorator, ensuring only one thread can check-and-update the cache at a time — without this, two threads could simultaneously see a cache miss and both compute (and potentially double-write) the same expensive result, or corrupt the dict during concurrent modification.
import threading, functools
def thread_safe_cache(func):
cache = {}
lock = threading.Lock()
@functools.wraps(func)
def wrapper(*args):
with lock:
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrapper
Real-world example
Building a thread-safe memoization decorator for a function called concurrently from multiple worker threads in a web server.
Likely follow-ups
Does functools.lru_cache already provide this same thread-safety guarantee internally, or would you still need to add your own locking?
The wrapper function itself must ALSO be declared 'async def' and use 'await' when calling the original coroutine — a plain synchronous wrapper calling an async function without awaiting it would just return an un-awaited coroutine object instead of the actual result.
import functools
def async_logged(func):
@functools.wraps(func)
async def wrapper(*args, **kwargs): # must ALSO be async
print(f"Calling {func.__name__}")
result = await func(*args, **kwargs) # must await the coroutine
return result
return wrapper
@async_logged
async def fetch_data():
await asyncio.sleep(1)
return "data"
Real-world example
Adding logging or timing behavior consistently to async functions in an asyncio-based application.
Likely follow-ups
How would you write a SINGLE decorator that correctly handles BOTH sync and async functions automatically?
Have the decorator STORE a reference to the decorated function in a shared registry (a dict or list, often a class attribute or module-level variable) as a SIDE EFFECT, while returning the ORIGINAL function UNCHANGED — the decorator's primary purpose here is registration, not wrapping/modifying behavior.
routes = {}
def route(path):
def decorator(func):
routes[path] = func # registers the function, but doesn't wrap/modify it
return func # returns the ORIGINAL function, unchanged
return decorator
@route("/users")
def list_users():
return ["Sam", "Alex"]
print(routes["/users"]()) # calls list_users() via the registry
Real-world example
Building a lightweight routing system, event handler registry, or plugin discovery mechanism using decorators purely for registration.
Likely follow-ups
Why does this registration-style decorator return the ORIGINAL function unchanged, unlike a typical wrapping decorator?
@functools.lru_cache(maxsize=N) automatically caches a function's return values keyed by its arguments, returning the cached result on repeated calls with the same arguments instead of recomputing — maxsize controls how many distinct argument combinations are cached before older ones are evicted (LRU policy).
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
fibonacci(30) # fast, thanks to automatic caching of overlapping subcalls
Real-world example
Speeding up a recursive Fibonacci calculation or an expensive pure computation called repeatedly with the same arguments.
Likely follow-ups
What does passing maxsize=None to lru_cache do, and when would that be risky for memory usage?