This question already has an answer here:
- Creating a singleton in Python 19 answers
There seem to be many ways to define singletons in Python. Is there a consensus opinion on Stack Overflow?
This question already has an answer here:
There seem to be many ways to define singletons in Python. Is there a consensus opinion on Stack Overflow?
The Singleton Pattern implemented with Python courtesy of ActiveState.
It looks like the trick is to put the class that's supposed to only have one instance inside of another class.
The Python documentation does cover this:
I would probably rewrite it to look more like this:
It should be relatively clean to extend this:
The one time I wrote a singleton in Python I used a class where all the member functions had the classmethod decorator.
Being relatively new to Python I'm not sure what the most common idiom is, but the simplest thing I can think of is just using a module instead of a class. What would have been instance methods on your class become just functions in the module and any data just becomes variables in the module instead of members of the class. I suspect this is the pythonic approach to solving the type of problem that people use singletons for.
If you really want a singleton class, there's a reasonable implementation described on the first hit on Google for "Python singleton", specifically:
That seems to do the trick.
The module approach works well. If I absolutely need a singleton I prefer the Metaclass approach.