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: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.
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.
.__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.
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
Become a Member to join the conversation.