This document presents a simple and elegant way to implement the Singleton design pattern in Python using the Memoization technique via the @cache
decorator from the standard library.
The Singleton pattern ensures that a class has only one single instance throughout the lifetime of an application.
This means that every time you instantiate the class, the same instance is returned.
Memoization is an optimization technique that stores the results of expensive function calls and returns the cached result when the same inputs occur again.
In Python, this is easily achieved using the @cache
decorator from the functools
module.
When you decorate a class with @cache
, Python treats calls to that class like calls to a function that returns an instance.
- The first time the class is instantiated, a new instance is created and stored in the cache.
- On subsequent calls with the same arguments (or no arguments), the cached instance is returned instead of creating a new one.
This effectively enforces the Singleton behavior — only one instance exists and is reused throughout your program.
- ✨ Simplicity: Implement Singleton in a single line without boilerplate code.
- ⚡ Performance: Avoid unnecessary instantiations, improving efficiency.
- 🧹 Clean Code: Reduces complexity and makes your code easier to maintain.
- 🧪 Testability: Predictable instance behavior simplifies testing and debugging.
- The
@cache
decorator requires that all arguments passed to the class constructor are hashable and immutable. - If your class takes mutable or varying arguments, this approach may not work as intended.
- This method is ideal for simple Singletons without dynamic instantiation parameters.