How do you implement a singleton pattern in Python?

A deep dive into the Singleton design pattern in Python, its importance, use cases and a step-by-step implementation guide. …

Updated August 26, 2023



A deep dive into the Singleton design pattern in Python, its importance, use cases and a step-by-step implementation guide.

The Singleton pattern is a classic design principle used to restrict the instantiation of a class to only one object. This means that no matter how many times you try to create an instance of the singleton class, you’ll always get the same, unique object. Think of it like a special key – there’s only one copy, and everyone who needs access uses that same key.

Why is this important in Python?

Understanding Singleton patterns showcases your grasp of object-oriented programming (OOP) concepts like:

  • Encapsulation: Singletons control how instances are created, hiding the complexity from outside code.
  • Design Patterns: Learning about Singleton prepares you to recognize and apply other valuable design patterns.

Let’s break down how to implement a Singleton in Python with a step-by-step guide:

Step 1: Define a Class for Your Singleton

class MySingleton:
    _instance = None  # Store the single instance (initially None)
  • _instance: This is a class attribute. The underscore _ suggests it’s intended for internal use within the class, though it’s not strictly private in Python.

Step 2: Create a Static Method for Instance Access

class MySingleton:
    # ... (previous code)

    @staticmethod
    def get_instance():
        if MySingleton._instance is None:
            MySingleton._instance = MySingleton()  
        return MySingleton._instance
  • get_instance(): This static method provides a controlled way to access the singleton instance.

    • It checks if _instance is None. If so, it creates a new instance of MySingleton and stores it in _instance.

    • Regardless of whether an instance already existed, it returns the stored _instance.

Step 3: Prevent Direct Instantiation (Optional)

class MySingleton:
    # ... (previous code)

    def __init__(self):
        if hasattr(MySingleton, "_instance"):
            raise Exception("This class is a singleton! Use get_instance() instead.") 
  • __init__(): This constructor method now checks if an instance already exists using hasattr(). If it does, it throws an exception to prevent creating duplicate instances.

Example Usage:

singleton1 = MySingleton.get_instance()
singleton2 = MySingleton.get_instance()

print(singleton1 is singleton2)  # Output: True

Both singleton1 and singleton2 will refer to the same object in memory.

Important Notes:

  • Global Access: Singleton instances are typically globally accessible, meaning they can be accessed from anywhere within your application.
  • Thread Safety: If you’re working with multi-threaded applications, additional measures might be needed to ensure thread safety when accessing the singleton instance.

Understanding the Singleton pattern gives you a powerful tool for managing shared resources and ensuring consistent behavior across different parts of your code.


Stay up to date on the latest in Computer Vision and AI

Intuit Mailchimp