Decorator Mechanics
A decorator is just a callable that takes a function and returns a replacement, so factories, stacking and lost metadata all follow from that rule. Interviewers use @ to test first-class functions.
part ofPythonoverview, primer and where to startread it →on this pageshowhide
explore
- Plain Decorators and @ Syntax3 questions
- Decorator Factories3 questions
- Stacking and Application Order3 questions
- functools.wraps and Metadata3 questions
- Stateful and Class-Based Decorators3 questions
- Decorating Classes4 questions
- Wrapping Methods and Descriptors4 questions
- Wrapping Coroutine Functions3 questions
- lru_cache and cached_property4 questions
- singledispatch Generic Functions4 questions
questions
page 2 of 2A flight-schedule differ stacks a retry decorator over one that opens an output file; how does that order decide whether handles leak?
basics
~20 sRetry re-invokes everything below it, so with retry on top the file wrapper runs once per attempt. That is correct only if it closes in a finally; otherwise each failed attempt of the 6,800-row diff strands a handle.
What goes wrong with a hand-rolled decorator that caches results in a plain dict?
basics
~20 sThe dict is created once at decoration time and never evicts, so it grows for the life of the process, pins whatever it holds, caches failures and stale values, breaks on unhashable arguments, and races under concurrent threads.
A @functools.wraps decorator changes a function's parameters - how do you keep inspect.signature honest?
basics
~10 sAssign an explicit inspect.Signature to the wrapper's signature attribute. inspect.signature checks signature before following wrapped, so build one from the original with Signature.replace(parameters=...) and the reported contract matches what the wrapper truly accepts.
When do you choose a class decorator over a mixin base class or a metaclass?
basics
~20 sChoose by reach and cost. A class decorator is a one-shot transform applied per class, visible at the point of use and easy to remove. A mixin joins the method resolution order and is inherited. A metaclass intercepts creation of a class and all its subclasses, and is the hardest to combine.
showing 31–34 of 34