Decorator Pattern in Python
Wrap an object to add behavior, such as logging or uppercasing, without editing its class. Stack as many wrappers as you need.
- Wrapping an object with the same interface
- Stacking several decorators
- How this relates to Python's @decorator syntax
Loggeradds "LOG: "LOG: HELLOUppercaseuppercasesHELLOMessagethe originalhello
Wrappers around the same interface
The problem
You want to add extra behavior to an object, such as logging, formatting or caching, without changing its class and without creating a subclass for every combination of extras.
Think of it like this
The Decorator pattern is like wrapping a gift. The gift stays the same; each layer of wrapping adds something, such as paper, then a ribbon, then a card. You can add layers in any order, and the result is still a gift you hand over the same way.
Message()🎁 The original giftUppercase(...)🧻 A layer that changes how it looksLogger(...)🎀 Another layer on top.render()🤲 Handed over the same way: LOG: HELLOThe Decorator pattern wraps an object in another object with the same interface, which calls the wrapped object and adds behavior before or after it.
Key points
Message.render()returns"hello".Uppercaseholds the wrapped object and returns its result in capital letters.Loggeradds"LOG: "in front of the wrapped object's result.Logger(Uppercase(Message())).render()stacks both wrappers, giving"LOG: HELLO".
When should you use it?
- Adding logging, caching, validation or formatting around existing objects.
- Combining optional extras without a subclass for each combination.
- Understanding Python's
@decoratorsyntax, which applies the same idea to functions.
When not to use it
- Only one fixed extra behavior is needed: change the class or add a method.
- Many layers that depend on each other's order: the stack becomes hard to understand.
Example code
class Message:
# Decorator: wrap an object to add behavior dynamically.
def render(self): return "hello"
class Uppercase:
def __init__(self, wrapped): self.wrapped = wrapped
def render(self): return self.wrapped.render().upper()
class Logger:
def __init__(self, wrapped): self.wrapped = wrapped
def render(self):
# Add behavior while preserving the render interface.
return "LOG: " + self.wrapped.render()
print(Logger(Uppercase(Message())).render())
Result of running the code
LOG: HELLO
Code explanation
Message, Uppercase and Logger all have a render() method. Uppercase calls render() on the object it wraps and changes the text to capitals, and Logger calls render() on its wrapped object and adds a prefix. Logger(Uppercase(Message())) therefore produces hello, then HELLO, then LOG: HELLO, one layer at a time.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Replace the sample domain while preserving the pattern structure.
- Compare the pattern with a simpler implementation and explain the tradeoff.
- Write tests for each participant before adding another implementation.
Common mistakes
Breaking the shared interface
A wrapper with a different method name cannot be wrapped again or used in place of the original.
class Uppercase:
def show(self): ...
class Uppercase:
def render(self): ...
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges