Real Python
Real Python

@realpython

5 Tweets 15 reads May 21, 2022
๐Ÿโš™๏ธ Python Tricks โ€” Ever needed to implement a Singleton in Python?
Hereโ€™s an example of coding a Singleton class with a .__new__() method that allows the creation of only one instance at a time
.__new__() checks the existence of previous instances cached on a class attribute
Here, Singleton doesnโ€™t provide an implementation of .__init__().
If you ever need a Singleton with a .__init__() method, keep in mind that this method runs every time you call the constructor.
This can cause weird initialization effects and bugs
Implementing a Singleton ensures a class has only one instance and provides a global point of access.
This design pattern solves problems by allowing it to control a class instantiation and restrict the number of instances.
Many 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 question is, have you ever needed to implement a Singleton in Python?

Loading suggestions...