Singleton

non-pythonic

class Database:
    __db = None
    def __init__(self):
        self.connection = "connection"
    @classmethod
    def create_connection(cls):
        if cls.__db:
           return cls.__db
        else:
           cls.__db = Database()
           return cls.__db

Some pythonic ways

class Database(object):
    __instance = None
    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = super().__new__(cls, *args, **kwargs)
        return cls.__instance
 
 
db1 = Database()
 
db2 = Database()
 
db1 is db2 # true

Singleton method in python is always avoided. It becomes hard to test singleton classes as everytime we need to reset the singleton object to its initial state.

Reference

  1. https://python-patterns.guide/gang-of-four/singleton/