Singleton Utility¶
The singleton utility provides a class decorator, allowing to easily create singleton classes.
-
class
xobox.utils.singleton.
Singleton
(decorated)[source]¶ Decorator class to turn any other class into a lazy singleton.
This class must be applied as a decorator instead of inheriting from this class.
Restrictions
- The decorated class can define one
__init__
function, but this constructor is restricted to theself
,*args
and**kwargs
arguments (in fact those must be present). - To get the singleton instance, the
get_instance()
method has to be used. Trying to use__call__
will result in aTypeError
being raised. - The actual instance will not be created before
get_instance()
has been called (lazy behaviour). - The decorated class cannot be inherited from. Therefore, this decorator can only be applied to final classes.
- This decorator shows good manners and takes care of
__doc__
,__module__
,__name__
,__annotations__
and__qualname__
context of the decorated class. This allows care-free handling in conjunction with automated documentation extraction tools such as Sphinx autodoc or similar.
Parameters: decorated – The Python class to be wrapped. -
get_instance
(*args, **kwargs)[source]¶ Returns the singleton instance. Upon its first call, it creates a new instance of the decorated class and calls its
__init__
method. On all subsequent calls, the already created instance is returned. :param args: positional arguments to be passed to the wrapped class’ constructor :param kwargs: keyword arguments to be passed to the wrapped class’ constructor :return: instance of the singleton-decorated class.
- The decorated class can define one