Skip to content

Latest commit

 

History

History
50 lines (29 loc) · 2.01 KB

File metadata and controls

50 lines (29 loc) · 2.01 KB

Singleton with @cache and Memoization in Python

Introduction

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.


What is the Singleton Pattern?

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.


What is Memoization?

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.


How Does @cache Enable Singleton Behavior?

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.


Why Use This Approach?

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

Important Considerations

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