This module provides a simple way to define a class as a singleton.
You can install this python module via pip:
pip install simple-singleton
Otherwise the module can be downloaded from PyPI: https://pypi.org/project/simple-singleton/
- Import the module:
or:
from simple_signleton import Singleton
from simple_signleton import SingletonArgs
- Create a class that uses one of the above meta classes:
or:
class NewClass(metaclass=Singleton): pass
class NewClass(metaclass=SingletonArgs): pass
The Singleton
class is a very basic implementation of the singleton pattern. All instances of a class are equal. Even if they are initialized with different parameters:
instance1 = SingletonClass(param="value")
instance2 = SingletonClass(param="different_value")
assert instance1 == instance2 # True
print(instance2.param) # "value"
If you do not want this behavior, use the SingletonArgs
meta class. With this class only instances that are initialized with the same parameters are the equal:
instance1 = SingletonArgsClass(param="value")
instance2 = SingletonArgsClass(param="different_value")
instance3 = SingletonArgsClass(param="value")
assert instance1 == instance2 # False
assert instance1 == instance3 # True
print(instance2.param) # "different_value"
The Singleton
and SingletonArgs
meta classes are not thread-safe!
To use them in a multi-threaded environment, please use the
ThreadSingleton
andThreadSingletonArgs
meta classes. They can be used exactly like the standard meta classes.