Skip to content

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

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.

Dionisio Cortés

Systems engineer and software engineering graduate. Some say I am a Java developer in decline, others a Pythonista on the rise; either way, I enjoy programming and tinkering with any language and technology.

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.

Dec 21, 2015

Comments

Leave a comment


This site uses Akismet to reduce spam. Learn how your comment data is processed.