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?
Singleton's half brother
I completely agree with staale and I leave here a sample of creating a singleton half brother:
a
will report now as being of the same class as singleton even if it does not look like it. So singletons using complicated classes end up depending on we don't mess much with them.Being so, we can have the same effect and use simpler things like a variable or a module. Still, if we want use classes for clarity and because in Python a class is an object, so we already have the object (not and instance, but it will do just like).
There we have a nice assertion error if we try to create an instance, and we can store on derivations static members and make changes to them at runtime (I love Python). This object is as good as other about half brothers (you still can create them if you wish), however it will tend to run faster due to simplicity.
Here's my own implementation of singletons. All you have to do is decorate the class; to get the singleton, you then have to use the
Instance
method. Here's an example:And here's the code:
There are also some interesting articles on the Google Testing blog, discussing why singleton are/may be bad and are an anti-pattern:
I think that forcing a class or an instance to be a singleton is overkill. Personally, I like to define a normal instantiable class, a semi-private reference, and a simple factory function.
Or if there is no issue with instantiating when the module is first imported:
That way you can write tests against fresh instances without side effects, and there is no need for sprinkling the module with global statements, and if needed you can derive variants in the future.
My simple solution which is based on the default value of function parameters.