10.1. Singleton

10.1.1. Rationale

  • EN: Singleton

  • PL: Singleton

  • Type: object

10.1.2. Use Cases

  • Database connection pool

  • HTTP Gateway

10.1.3. Design

10.1.4. Implementation

class Singleton:
    __instance = None

    def get_instance(cls):
        if not cls.__instance:
            cls.__instance = ...
        return cls.__instance

# Creating first instance for the first time
first = Singleton.get_instance()

# Connecting for the second time
# Will use existing instance
second = Singleton.get_instance()
class Singleton:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(*args, **kwargs)
        obj = cls._instance
        return obj

class MyClass(Singleton):
class DB:
    __connection = None

    def connect(cls):
        if not cls.__connection:
            print('Establishing connection...')
            cls.__connection = ...
        return cls.__connection

# Connecting for the first time
# Will establish new connection
first = DB.connect()

# Connecting for the second time
# Will use existing connection to the DB
# The same handle as `first`
second = DB.connect()
class Singleton(type):
    _instances = {}

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

class MyClass(metaclass=Singleton):

10.1.5. Assignments


Create assignments