Design Patterns in Python

Dhirendra JhaDhirendra Jha
3 min read

We all know about the design patterns and also know how crucial they are for structuring our code and also acing the interviews. So we are starting the series of design patterns covering all three types i.e. Creational, Structural and Behavioral and also implement them in python.

Lets start with Creational Pattern first.

Creational Pattern :- Baiscally a creational design pattern mainly focuses on the mechanisms of object creation. These patterns deal with how objects are created, aiming to make a system more flexible, reusable, and efficient by abstracting the instantiation process.

There are several Creational Design patterns stating below:-

Singleton Pattern, Factory Pattern, Abstract Factory Pattern, Builder Pattern, Prototype Pattern.

In this we will be learning about Singleton Pattern.

  • Singleton Pattern: It simply means, a class has only one instance i.e. only one object and that object is shared whenever that class is called.

Only one instance, i.e., one object, of a class will be created, and instead of creating a new object every time, the same existing object will circulate in the resources. Basically, that object is shared across the entire application.

Question: Why would someone want to create only one instance, and what’s the benefit of it?

  • The idea behind only one object creation is that in certain situations, creating multiple instances can cause problems or waste of resources. So, creating a single instance and reusing it becomes a better option.

  • Where is it used? Where global control is needed, such as:
    *
    Logging, Database connections, Resource sharing, Ensuring consistency in data behavior.*

lets look at the implementation of basic singleton in python.

class Singleton:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance  = super(Singleton, cls).__new__(cls)
        return cls._instance

    def is_singleton(self):
        print("Its singleton!!")


if __name__ == '__main__':
    s1 = Singleton()
    s2 = Singleton()

    s1.is_singleton()
    print(s1 is s2)
    print(s1 == s2)

lets understand the above code:

cls — This is a class parameter that represents the class. When you write Singleton() to create an object, the Singleton class itself is passed into cls.

new — This is a static method that gets called even before init and interferes with object creation to control it. That’s why it works with the class instead of the instance. new is a special method that handles the actual creation of the object — meaning it allocates memory and creates a new instance.

super(Singleton, cls) — This calls the superclass, i.e., the parent class, which in Python is the object class.

super(Singleton, cls).__new__(cls) — Here, it calls the new method of the parent class (i.e., the object class) and passes cls, which is the Singleton class. So basically, a new instance of the Singleton class is being created here.

cls._instance — The created instance is stored in this, and every time the class is called, it checks whether this variable has a value or not.

Why use super()?

If we directly used Singleton() or some other method, it would lead to infinite recursion because new would keep calling itself.

super() calls the new method of the parent class, which performs base-level object creation without recursion.”

Above example is the very basic for singleton. In next Part we will learn about how to keep singleton pattern thread safe and implement logging using single pattern in python.

Below is the Git repo for design patterns. If you want to learn together, feel free to fork it/star it.

https://github.com/dj221ai/Design-Patterns-In-Python

Thank you for reading.

2
Subscribe to my newsletter

Read articles from Dhirendra Jha directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Dhirendra Jha
Dhirendra Jha