singleton in python
singleton is a very useful design pattern in other static language like java and c++, because python has OOP design, so it’s not a bad idea to know how to implement a singleton design pattern in python.
main idea:
- hold a static variable
- use a private constructor as default, so the class can’t be instantiate by customer
- provide a public interface for user to get instance
in python, because there is no private constructor, so it’s not easy to get an enclosing scope for the class.
if you understand the singleton design pattern it’s not very difficult to implement it. what we really want with a Singleton is to have a single set of state data for all objects. That is, you could create as many objects as you want and as long as they all refer to the same state information then you achieve the effect of Singleton.
in python you can use __metaclass__ and decorator to do it.
- __metaclass__
- decorator
metaclass is the class of class. so it’s really useful for creating a class.
you can also use the __new__ to control the create of the new instance:
according to the idea: share the same state
use the metaclass to control the creation:
more easy and suggest way is to use the decorator to create the singleton class.
the last way use the python Closures, a function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope.
the message was still remembered although we had already finished executing the outer function and delete them. This technique by which some data (“Hello”) gets attached to the code is called closure in Python.
so come back to our singleton pattern using decorator: when the class decorated with singleton, the class will have an enclosing scope of instance.
if you want, you can use the module as a singleton and it will just be imported once.