mediumConceptCodingMidSenior
When does a decorator actually run, and what goes wrong when you stack two of them?
Decoration runs once, at definition time, so it happens on import rather than on call. Stacked decorators apply bottom-up and execute outermost-first, and each wrapper replaces the function's identity unless functools.wraps restores it, which is what breaks introspection and framework registration.
5 min readUpdated 2026-08-15Target archetype: Big Tech, Enterprise Captive, Product Startup
Answer
Short answer
Decoration runs once, at definition time, so it happens on import rather than on call.wraps restores it, which is what breaks introspection and framework registration.
Was this answer helpful?
Likely follow-ups
- Why does a decorator that reads configuration at import time make the code hard to test?
- What does inspect.signature do differently once __wrapped__ has been set?
- How would you write a decorator that works on both a plain function and an async one?
- Where would you put a per-instance cache instead of lru_cache on a method?
Related questions
- You put @functools.lru_cache on a method to speed it up, and the service's memory keeps growing. Why, and which fix do you choose?mediumAlso on functools4 min
- You cached something in a module-level dictionary. It works on your laptop and behaves oddly in production. What is different?mediumAlso on caching5 min
- How do you handle cache invalidation, and what goes wrong at scale?hardAlso on caching5 min
- Which status codes and method semantics do you insist on in a code review, how do the caching headers fit together, and is the API you just described REST?mediumAlso on caching6 min