Singleton Pattern in Python, with Examples
In this article we describe the Singleton pattern in Python, a pattern that makes sure a class has only one instance. Learn two ways to implement it.
Tool
- You can download the project for this post by clicking HERE.
- This tutorial is an adaptation of the tutorial Singleton Pattern in Java, with Examples.
The Singleton pattern is a creational pattern (Creational Design Pattern) whose goal is to guarantee that a class has only one instance and to provide a single point of access to that instance. This pattern is often used for logging (among other things), where we only want one instance of the logger that centralizes everything.
There are many ways to implement this pattern; we are going to look at two: a simple one, and another that is interesting because of its similarity to Java. You can find both at: The Singleton — Python 3 Patterns, Recipes and Idioms.
The way you would do it in Java
We can write an implementation similar to the one we would write in Java. What we do here is declare a private inner class (marked with __ ), since in Python we can’t have private constructors. In this private class we have the initialization method (__init__) and the method that converts the object to a string (__str__), so that we can see that it is always at the same memory location.
The first time we use the constructor (__new__) we create the instance, because the condition that we have no instance is met, and the rest of the times we don’t, simulating private constructors in Java. We can also see that the getters and setters are accessed through __getattr__ and __setattr__, which call those of the instance.
# coding=utf-8
class SoyUnico(object):
class __SoyUnico:
def __init__(self):
self.nombre = None
def __str__(self):
return `self` + ' ' + self.nombre
instance = None
def __new__(cls):
if not SoyUnico.instance:
SoyUnico.instance = SoyUnico.__SoyUnico()
return SoyUnico.instance
def __getattr__(self, nombre):
return getattr(self.instance, nombre)
def __setattr__(self, nombre, valor):
return setattr(self.instance, nombre, valor)
ricardo = SoyUnico()
ricardo.nombre = "Ricardo Moya"
print(ricardo)
ramon = SoyUnico()
ramon.nombre = "Ramón Invarato"
print(ramon)
print(ricardo)
print(ramon)
If we run it:
<__main__.__SoyUnico instance at 0x7f9f88b24878> Ricardo Moya
<__main__.__SoyUnico instance at 0x7f9f88b24878> Ramón Invarato
<__main__.__SoyUnico instance at 0x7f9f88b24878> Ramón Invarato
<__main__.__SoyUnico instance at 0x7f9f88b24878> Ramón Invarato
After running the code, we see that the variable is always at the same memory location (a single instance) and that it only holds the last value, because there is only one variable.
The simple way
We can use a simplified approach, where the first time (using the constructor again (__new__)) we instantiate the class because the __instance variable is none, and every other time, since it already has a value, we simply return it.
# coding=utf-8
class SoyUnico(object):
__instance = None
nombre = None
def __str__(self):
return `self` + ' ' + self.nombre
def __new__(cls):
if SoyUnico.__instance is None:
SoyUnico.__instance = object.__new__(cls)
return SoyUnico.__instance
ricardo = SoyUnico()
ricardo.nombre = "Ricardo Moya"
print(ricardo)
ramon = SoyUnico()
ramon.nombre = "Ramón Invarato"
print(ramon)
print(ricardo)
print(ramon)
Running the code, we get:
<__main__.SoyUnico object at 0x7f53d6226050> Ricardo Moya
<__main__.SoyUnico object at 0x7f53d6226050> Ramón Invarato
<__main__.SoyUnico object at 0x7f53d6226050> Ramón Invarato
<__main__.SoyUnico object at 0x7f53d6226050> Ramón Invarato
“Singleton Pattern in Python, with Examples” by Dionisio Cortés at jarroba.com, licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0. Registered at Safe Creative.

You may also like
Singleton Pattern in Java, with Examples
Learn the Singleton design pattern in Java: a software engineering pattern that limits the creation of objects of a class to one, with code examples.
Advanced Dockerfile: Multi-Stage Builds, Registries, and Tricks
Free Docker course. Expert Docker tricks: multi-stage builds, optimizing images, faster build times, and distributing images through Docker registries.


Leave a comment