A singleton pattern in Python

Source: Internet
Author: User

Original: 1190000008141049

The singleton pattern (Singleton pattern) is a commonly used software design pattern that is primarily intended to ensure that only one instance of a class exists . A singleton can come in handy when you want the entire system to have only one instance of a class.

For example, the configuration information for a server program is stored in a file, and the client reads the configuration file information through a AppConfig class. If the content of the configuration file needs to be used in many places during the run of the program, that is, many places need to create an instance of the AppConfig object, which leads to the existence of multiple AppConfig instance objects in the system, which can seriously waste memory resources. Especially if the configuration file has a lot of content. In fact, a class like AppConfig, we want only one instance object to exist during the run of the program.

In Python, we can implement a singleton pattern in a variety of ways:

    • Using modules

    • Use__new__

    • Using adorners (decorator)

    • Using meta-classes (Metaclass)

Using modules

In fact, thePython module is a natural singleton mode , because when the module is first imported, the file is generated .pyc , and when the second import, the file is loaded directly .pyc without executing the module code again. Therefore, we just need to define the relevant functions and data in a module, we can get a singleton object. If we really want a singleton class, consider doing this:

# mysingleton.py class My_singleton (object):     def foo (self):         Pass  = My_singleton ()

Save the above code in a file mysingleton.py , and then use:

 from Import My_singletonmy_singleton.foo ()
Use __new__

In order for a class to appear only one instance, we can use it __new__ to control the creation of the instance, with the following code:

class Singleton (object):     = None    def__new__(CLS, *args, * *kw)        :if not Cls._instance:            = Super (Singleton, CLS). __new__ (CLS, *args, * *kw          ) return cls._instance   class MyClass (Singleton):       = 1

In the above code, we associate an instance of the class with a class variable _instance , and if cls._instance None is created, the instance is returned directly cls._instance .

Implementation is as follows:

>>> one = MyClass ()>>> MyClass ()>>> one = = Twotrueis  twotrue>>> ID (one), id (4303862608, 4303862608)
Using adorners

We know that adorners (decorator) can dynamically modify the functionality of a class or function. Here, we can also use adorners to decorate a class so that it can generate only one instance, the code is as follows:

 from  functools import   wraps  def   Singleton (CLS): Instance  = {} @wraps (CLS)  def  getins Tance (*args, **kwargs):  if  cls not  in   Instance:insta NCE[CLS]  = CLS (*args, **kwargs)  return Instance[cls]  return   Getinstance@singleton  class   MyClass (object): A  = 1 

In the above, we define an adorner singleton , which returns an intrinsic function getinstance that determines whether a class is in a dictionary instances , and if it does not, it will be cls stored as key as cls(*args, **kw) value, instances otherwise, directly back instances[cls]

Using Metaclass

A meta-class (Metaclass) can control the creation of a class, and it mainly does three things:

    • Block creation of classes

    • Modifying the definition of a class

    • Returns the Modified class

The code to implement a singleton pattern using a meta class is as follows:

classSingleton (type): _instances= {}    def __call__(CLS, *args, * *Kwargs):ifCls not inchCls._instances:cls._instances[cls]= Super (Singleton, CLS).__call__(*args, * *Kwargs)returnCls._instances[cls]#Python2classMyClass (object):__metaclass__=Singleton#Python3#class MyClass (Metaclass=singleton):#Pass

A singleton pattern in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.