Implementing a Singleton in Pure Python
Learn how to implement the Singleton design pattern in pure Python to ensure only one instance of a class exists.
Implementing Singleton in Pure Python
The Singleton design pattern ensures a class has only one instance and provides a global point of access to it. This is useful when you want to control resources like database connections or configuration objects.
Why Use Singleton?
Singleton helps enforce a single shared state across your application. For example, you may need a central configuration object or a single logging instance.
Python Implementation
Unlike languages with private constructors, Python uses the __new__ method to control object creation.
Here’s how to create a Singleton class:
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
# Test Singleton
s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # True
This ensures any new instantiation returns the same object.
Key Takeaways
By overriding __new__, you control object creation and enforce single instance behavior in Python. Singleton should be used judiciously as it introduces global state.
Subscribe to Our YouTube for More
https://blog.arashtad.com/updates/implementing-a-singleton-in-pure-python/?feed_id=11242&_unique_id=686c776608bb2
Comments
Post a Comment