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.
pip install singleton-decoratorVerified import paths — ran on the pinned version, not inferred.
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.
Design your singleton's `__init__` to handle initial setup only. If dynamic reconfiguration is needed, provide a separate public method (e.g., `configure(new_value)`) on the singleton instance.
For unit testing or to access static/class methods of the original, undecorated class directly, use `YourClass.__wrapped__.your_method(obj)` (as demonstrated in the library's documentation) rather than `YourClass.your_method()`, especially when providing mock objects for `self`.
If your application operates in a multi-threaded environment and requires a truly thread-safe singleton, you must add explicit synchronization (e.g., using `threading.Lock`) within your class's initialization logic or consider a different thread-safe singleton implementation.
Evaluate whether the singleton pattern is truly the most appropriate design for your specific use case. Alternative patterns like dependency injection or factory methods can often lead to more modular and testable code.
No dependency data recorded yet.