Singletons in Python

Singletons in Python

Writing a singleton decorator to use with any class

Image for postPhoto by Patrick Schneider on Unsplash

Generally, we create many objects of classes according to our needs. Sometimes, creating multiple objects can be resource-intensive.

A real-world example can be the database connection class. You wouldn?t want to have multiple database objects because changes in one may make others inconsistent.

In these type of situations, we can use the singleton pattern. Using a singleton pattern, we ensure that a class creates only one instance.

There are several singletons in Python that you use frequently, including None, True, and False. It is the fact that None is a singleton that allows you to compare for None using the is keyword.

In Python, the typical way of creating a singleton pattern is using a decorator. You can read the article Decorators in Python to know more about decorators.

Suppose we want a single database connection throughout the life-cycle of our application. Let?s create a singleton class to serve our purpose.

Now, create the database connection class:

@Singletonclass DBConnection(object): def __init__(self): “””Initialize your database connection here.””” pass def __str__(self): return ‘Database connection object’

Let?s access this connection class:

c1 = DBConnection.Instance()c2 = DBConnection.Instance()print(“Id of c1 : {}”.format(str(id(c1))))print(“Id of c2 : {}”.format(str(id(c1))))print(“c1 is c2 ? ” + str(c1 is c2))

Output:

Id of c1 : 139699882512960Id of c2 : 139699882512960c1 is c2 ? True

If we do as below, we will get TypeError:

try: p = DBConnection()except TypeError as ex: print(“ERROR: {}”.format(ex.message))

I hope this article will help you to implement the singleton pattern in any class.

19