I am having a situation where I have to make sure I only have one object. I am thinking about implementing singleton like following:
class One_Of_a_Kind:
def __init__(self):
self.do_some_setup()
class One_Creator:
Only_One = None
def __new__(cls, *args, **kwargs):
if One_Creator.Only_One:
return One_Creator.Only_One
else:
One_Creator.Only_One = One_of_a_Kind()
return One_Creator.Only_One
Since I am reading a lot about singleton (pros and cons), I am little hesitant in implementing this code. I would like to know if it is okay and/or considered good practice to use in a situation where only one object of certain class in needed ( or mandatory).
Is there a better way of implementing the same thing?
A better way is the Borg design pattern. It's very simple to implement in python:
class Borg:
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
You don't actually have a single instance, but each instance shares the same state - which is the part that matters.
When and how to use a singleton is a pretty broad question and primarily opinion based. That being said, I would implement it like this:
class Singleton(object):
state = {}
def __init__(self):
self.__dict__ = Singleton.state
The idea is taken from here. This is sort of a pseudo-singleton, as two instance will not share the same id:
>>> s1 = Singleton()
>>> s2 = Singleton()
>>> s1 is s2
False
>>> s1.x = 42
>>> s2.x
42
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With