🎉 Hooray! After 3 years of work, I've finally released the ebook on design patterns! Check it out »
Singleton

Singleton in Python

Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides single point of access to it for any other code.

Singleton has almost the same pros and cons as global variables. Although they’re super-handy, they break modularity of your code.

You can just use a class, which depends on Singleton, in some other context. You’ll have to carry the Singleton class as well. Most of the time, this limitation comes up during the creation of unit tests.

Learn more about Singleton

Usage of the pattern in Python

Complexity:

Popularity:

Usage examples: A lot of developers consider the Singleton pattern an antipattern. That’s why its usage is on the decline in Python code.

Identification: Singleton can be recognized by a static creational method, which returns same cached object.

Naïve Singleton

It’s pretty easy to implement a sloppy Singleton. You just need to hide constructor and implement a static creational method.

Same class behaves incorrectly in a multithreaded environment. Multiple threads can call creational method simultaneously and get several instances of Singleton class.

main.py: Conceptual Example

from __future__ import annotations
from typing import Optional


class Singleton:
    """
    The Singleton class defines the `getInstance` method that lets clients
    access the unique singleton instance.
    """

    _instance: Optional<a href="/design-patterns/singleton">Singleton</a> = None

    def __init__(self) -> None:
        if Singleton._instance is not None:
            raise ReferenceError("Cannot instantiate a singleton class.")
        else:
            Singleton._instance = self

    @staticmethod
    def get_instance() -> Singleton:
        """
        The static method that controls the access to the singleton instance.
        
        This implementation let you subclass the Singleton class while
        keeping just one instance of each subclass around.
        """

        if not Singleton._instance:
            Singleton()
        return Singleton._instance

    def some_business_logic(self):
        """
        Finally, any singleton should define some business logic, which can
        be executed on its instance.
        """

        # ...


if __name__ == "__main__":
    # The client code.

    s1 = Singleton.get_instance()
    s2 = Singleton.get_instance()

    if id(s1) == id(s2):
        print("Singleton works, both variables contain the same instance.")
    else:
        print("Singleton failed, variables contain different instances.")

Output.txt: Output

Singleton works, both variables contain the same instance.

Singleton in Other Languages

Singleton in Java Singleton in C# Singleton in PHP Singleton in TypeScript