Ways to use singleton in Python
- using module
- using method
__new__
- using decorator
- using metaclass
Analysis the singleton with method __new__
Implementation
Let us see the code first:
1 | class Singleton(object): |
And check the result:
1 | s1 = Singleton() |
How does it work?
We should know two feature to understand that:
- Class variables are shared by all instances of the class. (Learn more in document.)
- The
__new__
method return a instance of class which will be used asself
in__init__
and other methods. (Learn more in document)
Here we go
When declaring a new instance, the __new__
method check the existance of the class variable _instance
. Return it if exists. Otherwise, the class creates a new one, assigns to _instance
and return.
After that, all instances of the class Singleton
are the same class variable of class Singleton
.
Implement with decorator
Implementation
1 | def singleton(cls): |
Let us check the result
1 |
|
How it works?
- The criticle point is the implementation of closure in python. The variable
_instances
above did not collected by GC afterMyClass
was called. (You can learn more here)
Analysis the singleton with method metaclass
Implementation
1 | class Singleton(type): |
Check the result
1 | class MyClass(metaclass=Singleton): # in Python 3 |
How it works?
- All class is an instance of a metaclass.
- When the class is called it return the result which the
__call__
method of metaclass return. (If not be overrided.) - So we return the same instance by means of the shared class variable
_instances
in metaclassSingleton
to return a same instance. - By the way, the parent of metaclass should be the class
type
.