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:
and that’s it! Use MySingleton.INSTANCE and you got yourself a singleton. Well, in Python it’s more cumbersome (enums in Java are pretty awesome and hard to compete with, even with Python’s general awesomeness). I suggested using a singleton metaclass, but it was turned down for being too complicated. Well, let’s take a look at some other implementation ideas I’ve heard, and we’ll look at the metaclass alternative at the end:
Provide a get_instance method and make __init__ throw (fine, fine, raise) an exception if it was called twice:
Cons: Using get_instance is ugly and non-intuitive.
Implementing an inner class as your ‘main class’ and the external one as a wrapper:
Cons: This implementation is definitely not beautiful. Also, it prevents users from subclassing the business logic class.
Implementing a ‘singleton’ decorator for classes:
Cons: This code turns MyClass into a factory function, so you can’t subclass it or use ‘isinstance’, etc.
Implementing a SingletonType metaclass:
Cons: Other than some people considering metaclasses to be black magic, none that I can think of (besides general ‘singletons are evil’ complaints).