pathex.adts.singleton module

Singleton decorator

Module

pathex.adts.singleton


This module provides a singleton() decorator. Although it may seem that this has little usefulness in Python (because its inherent dynamic nature), the idea is to diminsh the possibilities in that an error may be committed, and to enforce some memory optimization by using only one instance of the decorated class.

Caution

The content of this module is not intended to be part of the exposed main features of PathEx, so it may change in the future. It is documented here only because it is part of the current internal design of the library.

singleton(wrapped_class: type[~ T]) type[~T][source]

Makes a class singleton

Use it as a decorator:

>>> from dataclasses import dataclass
>>> @singleton
... @dataclass(init=False)
... class SingletonClass:
...     attribute: int
...
...     def __init__(self, attribute: int):
...         self.attribute = attribute + 1

Any call to the class will return the same object. The first call will make proper initialization, but subsequent calls will ignore the arguments. It is allowed to call the class without arguments after the first call. Use the class call instead or a previously assigned variable.

>>> try:
...     SingletonClass()
... except TypeError:
...     pass # Right!
... else:
...     print('Wrong')
>>> instance = SingletonClass(23)
>>> assert instance is SingletonClass(44) is SingletonClass() is SingletonClass(11)
>>> assert SingletonClass().attribute == instance.attribute == 24
>>> assert not hasattr(SingletonClass(), 'instance')

Singleton classes can not be subclassed:

>>> try:
...     class B(SingletonClass):
...         pass
... except TypeError:
...     pass # Right!
... else:
...     print('Wrong!')

The representation of the singleton instance is constructed from the name of the class:

>>> assert repr(SingletonClass()) == '<SINGLETON_CLASS>'
>>> @singleton
... class _A_Class:
...     pass
>>> assert repr(_A_Class()) == '<_A_CLASS>'