Few years ago I found an implementation of the Singleton pattern in Python by Duncan Booth:
class Singleton(object):
\"\"\"
Singleton class by Duncan Boo
You need to drop any additional arguments you are passing when you construct the object. Change the offending line to:
cls._instance = object.__new__(cls)
or
cls._instance = super(Singleton, cls).__new__(cls)
though I think you'll be fine with the first (diamond inheritance and singletons sound as though they shouldn't be mixed).
P.S. I did try this suggestion and it works for me so I don't know why it didn't work for you.
Edit in response to @dragonx's comment: As pointed out in the comments, object.__new__
will throw an exception if you pass on *args, **kwargs
so the super call to __new__
should not include any arguments apart from cls
. This wasn't the case when the original article was written. Also of course if you choose to base your singleton on some other type such as a tuple
you would then need to pass the appropriate arguments.