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?
As the accepted answer says, the most idiomatic way is to just use a module.
With that in mind, here's a proof of concept:
See the Python data model for more details on
__new__
.Example:
Notes:
You have to use new-style classes (derive from
object
) for this.The singleton is initialized when it is defined, rather than the first time it's used.
This is just a toy example. I've never actually used this in production code, and don't plan to.
In cases where you don't want the metaclass-based solution above, and you don't like the simple function decorator-based approach (e.g. because in that case static methods on the singleton class won't work), this compromise works:
I don't really see the need, as a module with functions (and not a class) would serve well as a singleton. All its variables would be bound to the module, which could not be instantiated repeatedly anyway.
If you do wish to use a class, there is no way of creating private classes or private constructors in Python, so you can't protect against multiple instantiations, other than just via convention in use of your API. I would still just put methods in a module, and consider the module as the singleton.
Here is an example from Peter Norvig's Python IAQ How do I do the Singleton Pattern in Python? (You should use search feature of your browser to find this question, there is no direct link, sorry)
Also Bruce Eckel has another example in his book Thinking in Python (again there is no direct link to the code)
You can override the
__new__
method like this:Creating a singleton decorator (aka an annotation) is an elegant way if you want to decorate (annotate) classes going forward. Then you just put @singleton before your class definition.