TL;DR: Use metaclasses - see #4 on the list
I recently heard some people at work talking about ways to implement the Singleton pattern in Python. I’m fairly new to Python, and for me, the most elegant Singleton definition would be in Java:
This is a companion discussion topic for the original entry at http://amir.rachum.com/blog/2012/04/26/implementing-the-singleton-pattern-in-python/
no! don't use metaclasses! you can create singletons very easily using class decorators:
def singleton(cls):
return cls()
@singleton
class Foo(object):
def bar(self):
...
Foo.bar()
there, Foo is a singleton object, and you can't create any more instances, because you lose reference to the class (of course you can use Foo.__class__() and create a new instance, but you can always shoot yourself in the leg).
metaclasses are not evil -- they are a stupid feature and you can always find better ways to solve the problem, that don't involve messing with the barzelim. in fact, you can even emulate metaclasses using class decorators, but that's a another discussion.
just to note: subclassing singletons doesn't make sense, so it can't be considered a cons
This is nice and simple, but using Foo instead of Foo() is not intuitive and it doesn't allow you to use isinstance without accessing Foo.__class__.
Well, None, True and False are singletons, and they don't require parentheses... Besides, why would you want to "instantiate " singleton classes? They are concrete objects.
And just like you don't use isinstance(x, None) but "x is None", you should use the same here.