Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Allowing Only a Single Instance in Your Class

00:00 Allowing Only a Single Instance in Your Classes. Sometimes you need to implement a class that only allows the creation of a single instance. This type of class is commonly known as a singleton class.

00:14 In this situation, the .__new__() method comes in handy because it can help you restrict the number of instances that a given class can have.

00:24 Note that most experienced Python developers would argue that you don’t need to implement the singleton design pattern in Python unless you already have a working class and need to add the pattern’s functionality on top of it. The rest of the time, you can use a module-level constant to get the same singleton functionality without having to write a relatively complex class.

00:46 Here’s an example of coding a Singleton class with a .__new__() method that allows the creation of only one instance at a time. To do this, .__new__() checks the existence of previous instances cached on a class attribute.

01:01 The Singleton class in this example has a class attribute called .__instance that defaults to None and works as a cache.

01:09 The .__new__() method checks if no previous instance exists by checking whether this attribute is None. If this condition is true, then the if code block creates a new instance of Singleton and stores it to cls._instance. Finally, the method returns the new or the existing instance to the caller.

01:30 The first example of the Singleton class is instantiated as first, and the second example is instantiated as second.

01:38 Comparing the identity of the objects with the is operator shows that both objects are the same object. The names first and second just hold references to the same Singleton object.

01:53 Note that in this example, Singleton doesn’t provide an implementation of .__init__(). If you ever need a class like this with an .__init__() method, then keep in mind that this method will run every time you call the Singleton constructor.

02:05 This behavior can cause weird initialization effects and bugs. Coming up next, you’ll see how to partially emulate a popular part of the Python standard library, collections.namedtuple.

Become a Member to join the conversation.