Singleton in Python

Divya Khatnar
3 min readFeb 7, 2023

An easy guide on with concept of singletons in python with examples

Credits: Stock up

A singleton is a design pattern in which a class has only one instance and provides a global point of access to it. In Python, a singleton can be implemented by using a class decorator, a metaclass, or a module-level variable. The key idea behind a singleton is to ensure that only one instance of the class is created, even if multiple instances are requested.
Some common examples of singleton in Python include:

  1. Database Connections: To ensure that only one database connection is created and used throughout the application.
  2. Loggers: To ensure that only one logger instance is used throughout the application.
  3. Caches: To ensure that the cache data is shared across the application and there’s only one instance of cache.
  4. Configuration Manager: To ensure that there’s only one instance of configuration data that can be used throughout the application.
  5. Thread-Safe Resources: To ensure that only one instance of a shared resource is created and used in a multi-threaded environment.

These are just a few examples, and the singleton pattern can be used in various other situations where a unique instance of an object is needed.

There are several ways to create a singleton class in Python:

  1. Using a class decorator
def singleton(cls):
instances = {}
def getinstance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return getinstance

@singleton
class MySingletonClass:
...

2. Using a metaclass

class Singleton(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 MySingletonClass(metaclass=Singleton):
...

3. Using a module level variable

class MySingletonClass:
...

_singleton_instance = None
def get_singleton_instance(*args, **kwargs):
global _singleton_instance
if not _singleton_instance:
_singleton_instance = MySingletonClass(*args, **kwargs)
return _singleton_instance

Each of these methods ensures that only one instance of the class is created and shared globally. You can choose the one that fits your needs best.

Here are a few reasons why you might want to use a singleton:

  1. Global Access: A singleton class provides a single point of access to its instance, which can be used anywhere in the code. This makes it easy to access the instance from any part of the system without having to pass it around as an argument.
  2. Centralized Control: By having only one instance of a class, it’s easier to maintain control over the state of the system and avoid inconsistencies.
  3. Memory Management: Singletons can be used to manage resources efficiently, especially those that are expensive to create and maintain. By having only one instance of the class, you can reduce the amount of memory used by the system.
  4. Configuration Management: Singletons can be used to store configuration data and provide access to it from throughout the system. This makes it easy to manage configuration changes and avoid inconsistencies.
  5. Thread Safety: Singletons can be used to manage resources that need to be shared across multiple threads. By having only one instance of the class, you can avoid race conditions and other concurrency issues.

If you like the article please don’t forget to clap (or multiple claps) and follow for more :)

--

--