skip to content

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 pageshow

questions

page 2 of 2

A flight-schedule differ stacks a retry decorator over one that opens an output file; how does that order decide whether handles leak?

level: seniorimportance: should knowfreq 28%

basics

~20 s

Retry 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.

open as a page

What goes wrong with a hand-rolled decorator that caches results in a plain dict?

level: seniorimportance: should knowfreq 45%

basics

~20 s

The 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.

open as a page

A @functools.wraps decorator changes a function's parameters - how do you keep inspect.signature honest?

level: seniorimportance: should knowfreq 30%

basics

~10 s

Assign 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.

open as a page

When do you choose a class decorator over a mixin base class or a metaclass?

level: principalimportance: should knowfreq 35%

basics

~20 s

Choose 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.

open as a page

showing 31–34 of 34