Implementation of the singleton pattern under Python

  • 2020-04-02 13:53:41
  • OfStack

Many developers considered implementing the singleton pattern like c++ when they first started learning Python, but later found out that c++ is c++ and Python is Python and cannot be easily imitated.

A common approach in Python is to implement singletons with global or class variables. This article describes how to implement the singleton pattern with decorators. The sample code is as follows:


##----------------------- code begin -----------------------

# -*- coding: utf-8 -*-
def singleton(cls):
"""Define a class with a singleton instance."""
instances = {}
def getinstance(*args, **kwds):
return instances.setdefault(cls, cls(*args, **kwds))
return getinstance
 
##1  The future version Python support Class Decorator You can use it like this 
class Foo(object):
def __init__(self, attr=1):
self.attr = attr

Foo = singleton( Foo ) ##2 2.5 And previous version not supported Class Decorator You can use it like this 

if __name__ == "__main__":
ins1 = Foo(2) #  Equivalent to : ins1 = singleton(Foo)(2)
print "Foo(2) -> id(ins)=%d, ins.attr=%d, %s" % (id(ins1), ins1.attr, ('error', 'ok')[ins1.attr == 2])
ins2 = Foo(3)
print "Foo(3) -> id(ins)=%d, ins.attr=%d, %s" % (id(ins2), ins2.attr, ('error', 'ok')[ins2.attr == 2])
ins2.attr = 5
print "ins.attr=5 -> ins.attr=%d, %s" % (ins2.attr, ('error', 'ok')[ins2.attr == 5])
 
##------------------------ code end ------------------------

Output:


Foo(2) -> id(ins)=19295376, ins.attr=2, ok
Foo(3) -> id(ins)=19295376, ins.attr=2, ok
ins.attr=5 -> ins.attr=5, ok

Related articles: