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?
See this implementation from PEP318, implementing the singleton pattern with a decorator:
OK, singleton could be good or evil, I know. This is my implementation, and I simply extend a classic approach to introduce a cache inside and produce many instances of a different type or, many instances of same type, but with different arguments.
I called it Singleton_group, because it groups similar instances together and prevent that an object of the same class, with same arguments, could be created:
Every object carries the singleton cache... This could be evil, but it works great for some :)
I'm very unsure about this, but my project uses 'convention singletons' (not enforced singletons), that is, if I have a class called
DataController
, I define this in the same module:It is not elegant, since it's a full six lines. But all my singletons use this pattern, and it's at least very explicit (which is pythonic).
A slightly different approach to implement the singleton in Python is the borg pattern by Alex Martelli (Google employee and Python genius).
So instead of forcing all instances to have the same identity, they share state.