Skip to content

Reference

Singleton types.

Example

from solus import Singleton

class Null(Singleton):
    ...

null = Null()

singleton = Singleton() module-attribute

The singleton instance.

unsafe_singleton = UnsafeSingleton() module-attribute

The unsafe singleton instance.

Singleton

The singleton type.

Source code in solus/core.py
66
67
68
69
70
class Singleton(metaclass=SingletonType):
    """The singleton type."""

    def __repr__(self) -> str:
        return get_type_name(self)

SingletonType

Bases: type

The singleton meta type, used to implement singleton types.

Source code in solus/core.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class SingletonType(type):
    """The singleton meta type, used to implement singleton types."""

    _INSTANCES = {}  # type: ignore
    _LOCK = Lock()

    def __call__(cls: Type[S], *args: Any, **kwargs: Any) -> S:
        instances = cls._INSTANCES  # type: ignore
        lock = cls._LOCK  # type: ignore

        # use double-checked locking

        if cls not in instances:
            with lock:
                if cls not in instances:
                    instances[cls] = super().__call__(*args, **kwargs)  # type: ignore

        return instances[cls]  # type: ignore

UnsafeSingleton

The unsafe singleton type.

Source code in solus/core.py
35
36
37
38
39
class UnsafeSingleton(metaclass=UnsafeSingletonType):
    """The *unsafe* singleton type."""

    def __repr__(self) -> str:
        return get_type_name(self)

UnsafeSingletonType

Bases: type

The unsafe singleton meta type, used to implement unsafe singleton types.

Source code in solus/core.py
21
22
23
24
25
26
27
28
29
30
31
32
class UnsafeSingletonType(type):
    """The *unsafe* singleton meta type, used to implement *unsafe* singleton types."""

    _INSTANCES = {}  # type: ignore

    def __call__(cls: Type[S], *args: Any, **kwargs: Any) -> S:
        instances = cls._INSTANCES  # type: ignore

        if cls not in instances:
            instances[cls] = super().__call__(*args, **kwargs)  # type: ignore

        return instances[cls]  # type: ignore