A Testable Singleton Decorator

1.0.0 · maintenance · verified Mon Apr 13

The `singleton-decorator` is a Python library (version 1.0.0, last released in 2017) that provides a simple decorator to implement the singleton design pattern for classes. It aims to address common pitfalls of other singleton implementations, specifically making the decorated classes more amenable to unit testing by exposing the original class via a `__wrapped__` attribute. The library is stable but not actively developed.

Warnings

Install

Imports

Quickstart

This example demonstrates how to apply the `@singleton` decorator to a class. It shows that only one instance of `MyClass` is ever created, and subsequent calls to the constructor will return the existing instance without re-running `__init__`. It also highlights how to access the original, undecorated class using `__wrapped__` for testing purposes.

from singleton_decorator import singleton

@singleton
class MyClass:
    def __init__(self, value=0):
        self.value = value
        print(f"MyClass initialized with value: {self.value}")

    def get_value(self):
        return self.value

# First instance creates and initializes
obj1 = MyClass(10)
print(f"Obj1 value: {obj1.get_value()}")

# Second instance returns the same object, __init__ is NOT called again
obj2 = MyClass(20) # Arguments are ignored after the first call
print(f"Obj2 value: {obj2.get_value()}")
print(f"Are obj1 and obj2 the same instance? {obj1 is obj2}")

# Accessing the original class for testing or static methods
# Note: Use __wrapped__ for direct class method calls or inspection in tests
print(f"Accessing original class via __wrapped__: {MyClass.__wrapped__.__name__}")

view raw JSON →