Glossary

Decorator Pattern

The decorator pattern is a structural design pattern (from the Gang of Four's Design Patterns) that attaches additional responsibilities to an object dynamically by wrapping it in a decorator object. In Python, the term "decorator" usually refers to the @ syntax for wrapping functions and classes, which is a related but distinct concept.

Python's @decorator syntax is inspired by the decorator pattern but is simpler: it replaces a function (or class) with the return value of a callable. The classical OOP decorator pattern wraps an object in another object that has the same interface, delegating calls while adding behaviour (logging, caching, access control). Both achieve the same goal — extending behaviour without modifying the original — but the mechanisms differ.

In practice, Python programmers use both approaches. The @ syntax handles the common case of wrapping functions and classes. The classical decorator pattern is used when you need to wrap arbitrary objects at runtime, compose multiple behaviours dynamically, or work in an inheritance-based design. Python's dynamic nature and duck typing make the classical pattern straightforward to implement: the wrapper just needs to support the same methods as the wrapped object.

Related terms: Decorator, Composition, Duck Typing

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.