pysingleton

raw JSON →
0.2.1 verified Mon Apr 27 auth: no python maintenance

A minimal Python library providing a @singleton decorator to turn classes into singletons. Version 0.2.1, released Oct 2014. It is in maintenance mode with rare updates.

pip install pysingleton
error ImportError: No module named pysingleton
cause Library not installed, or wrong Python environment.
fix
Run 'pip install pysingleton' and ensure the correct Python interpreter is active.
error TypeError: 'str' object is not callable when using @singleton
cause Forgot to call the decorator; used @singleton instead of @singleton().
fix
Use @singleton (no parentheses) as it directly accepts the class.
error AttributeError: 'MyClass' object has no attribute '_instance'
cause Manually accessing _instance before instantiation.
fix
Call MyClass() to create the singleton instance first; then use MyClass()._instance.
gotcha Locking in __init__: The singleton decorator does not protect against concurrent instantiation. In multithreaded environments, __init__ may be called multiple times.
fix Add a threading lock inside the class's __new__ method or use a thread-safe singleton pattern.
gotcha Subclassing singletons: Subclassing a singleton class may lead to unexpected behavior. The subclass is not automatically a singleton.
fix Avoid subclassing singletons; apply @singleton to each class individually.
deprecated Python 2 support: The library was built for Python 2 and may have compatibility issues with Python 3 (e.g., metaclass syntax).
fix Use Python 3 compatible libraries like 'singledispatch' or custom metaclass for production code.

Apply @singleton to a class to ensure only one instance exists.

from pysingleton import singleton

@singleton
class MyClass:
    pass

a = MyClass()
b = MyClass()
assert a is b
print("Singleton works")