I have this very simple program that has a singleton implemented as a base class that simply defines a new that is used implement the "single-ness". However I can no longer send arguments to the init method - when I do I get a "TypeError: object() takes no parameters" from the singleton new super call:
class Singleton(object):
_instances = {}
def __new__(cls, *args, **kwargs):
print(args, kwargs)
if cls._instances.get(cls, None) is None:
cls._instances[cls] = super(Singleton, cls).__new__(cls, *args, **kwargs)
return Singleton._instances[cls]
class OneOfAKind(Singleton):
def __init__(self):
print('--> OneOfAKind __init__')
Singleton.__init__(self)
class OneOfAKind2(Singleton):
def __init__(self, onearg):
print('--> OneOfAKind2 __init__')
Singleton.__init__(self)
self._onearg = onearg
x = OneOfAKind()
y = OneOfAKind()
print(x == y)
X = OneOfAKind2('testing')
The output is:
() {}
Traceback (most recent call last):
File "./mytest.py", line 29, in <module>
x = OneOfAKind()
File "./mytest.py", line 10, in __new__
cls._instances[cls] = super(Singleton, cls).__new__(cls, (), {})
TypeError: object() takes no parameters
Right, because object which is what you are inheriting from and calling from super does not take any args:
In [54]: object('foo', 'bar')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-54-f03d0963548d> in <module>()
----> 1 object('foo', 'bar')
TypeError: object() takes no parameters
if you want to do something like this, I recommend a metaclass instead of subclassing, and instead of overriding __new__ the metaclass overrides __call__ for object creation:
import six ## used for compatibility between py2 and py3
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if Singleton._instances.get(cls, None) is None:
Singleton._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return Singleton._instances[cls]
@six.add_metaclass(Singleton)
class OneOfAKind(object):
def __init__(self):
print('--> OneOfAKind __init__')
@six.add_metaclass(Singleton)
class OneOfAKind2(object):
def __init__(self, onearg):
print('--> OneOfAKind2 __init__')
self._onearg = onearg
Then:
In [64]: OneOfAKind() == OneOfAKind()
--> OneOfAKind __init__
Out[64]: True
In [65]: OneOfAKind() == OneOfAKind()
Out[65]: True
In [66]: OneOfAKind() == OneOfAKind2('foo')
Out[66]: False
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