Skip to content

singleton

Singleton #

Bases: type

Meta class used to declare singleton

Example:

from dataclasses import dataclass


@dataclass
class Data(metaclass=Singleton):
    name: str = ""


data = Data()
print(data)            # output: Data(name='')
data.name = "foo"
print(data)            # output: Data(name='foo')
print(Data())          # output: Data(name='foo')
print(data is Data())  # output: True
Source code in cogip/utils/singleton.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Singleton(type):
    """
    Meta class used to declare singleton

    Example:

        from dataclasses import dataclass


        @dataclass
        class Data(metaclass=Singleton):
            name: str = ""


        data = Data()
        print(data)            # output: Data(name='')
        data.name = "foo"
        print(data)            # output: Data(name='foo')
        print(Data())          # output: Data(name='foo')
        print(data is Data())  # output: True
    """

    _instance = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instance:
            cls._instance[cls] = super().__call__(*args, **kwargs)
        return cls._instance[cls]