Wednesday, June 10, 2026

Singleton Example in Python


All Questions From This Chapter    « Previously    Next »

can you explain this line by line in layman terms:

class SingletonMeta(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 Database(metaclass=SingletonMeta):
    pass

db1 = Database()
db2 = Database()
assert db1 is db2




Yes — this code is a Singleton pattern, which means it makes sure only one object of a class is ever created.

Here is the line-by-line meaning in simple terms:

Python
class SingletonMeta(type):

This creates a custom metaclass.
A metaclass is like a “class for classes” — it controls how classes behave when they are created or called.

Python
    _instances = {}

This is a dictionary used to store created objects.
It keeps track of whether an object for a class has already been made.

Python
    def __call__(cls, *args, **kwargs):

This defines what happens when you do something like Database().
Normally, calling a class creates a new object. Here, we are changing that behavior.

  • cls means the class being called, like Database

  • *args and **kwargs mean any arguments passed to the class

Python
        if cls not in cls._instances:

This checks: “Has an object of this class already been created?”

  • If not, create one

  • If yes, reuse the old one

Python
            cls._instances[cls] = super().__call__(*args, **kwargs)

This creates the object in the normal way and stores it in _instances.

So the first time you call Database(), it makes a real object and saves it.

Python
        return cls._instances[cls]

This returns the stored object every time.

So after the first creation, every later call gives back the same object.


Python
class Database(metaclass=SingletonMeta):

This creates a class called Database, but instead of using the normal class behavior, it uses SingletonMeta.

That means Database() will follow the singleton rule.

Python
    pass

This means the class has no extra code inside it right now.


Python
db1 = Database()
db2 = Database()

Both lines try to create a Database object.

But because of the singleton logic:

  • db1 gets the first and only object

  • db2 gets the same exact object, not a new one

Python
assert db1 is db2

This checks whether db1 and db2 are literally the same object in memory.

is means “same object”, not just “same value”.

This assertion passes because both variables point to the same singleton instance.


In plain English:

This code says:
“No matter how many times someone tries to create a Database, always return the same one.”

A simple real-life example is a printer service, config manager, or database connection manager where you want only one shared instance.


All Questions From This Chapter    « Previously    Next »
Tags: Python,Algorithms,

No comments:

Post a Comment