Home > Backend Development > Python Tutorial > Five ways to implement singleton mode in Python

Five ways to implement singleton mode in Python

WBOY
Release: 2023-05-26 22:31:24
forward
1577 people have browsed it

Python 实现单例模式的五种写法

Singleton Pattern is a commonly used software design pattern. The main purpose of this pattern is to ensure that only one instance of a certain class exists. Singleton objects come in handy when you want only one instance of a certain class to appear in the entire system.

For example, the configuration information of a server program is stored in a file, and the client reads the configuration file information through an AppConfig class. If the contents of the configuration file need to be used in many places during the running of the program, that is to say, instances of the AppConfig object need to be created in many places, which will lead to the existence of multiple AppConfig instance objects in the system, and this will seriously waste memory. resources, especially if the configuration file contains a lot of content.

In fact, for a class like AppConfig, we hope that only one instance object will exist during the running of the program.

In Python, we can use a variety of methods to implement the singleton pattern:

  1. Using modules
  2. Using decorators
  3. Using classes
  4. Implemented based on __new__ method
  5. Implemented based on metaclass method

Let’s follow Detailed introduction:

Using modules

In fact, Python modules are natural singleton mode, because when the module is imported for the first time, a .pyc file will be generated. When imported for the second time, the .pyc file will be loaded directly without executing the module code again.

Therefore, we only need to define the relevant functions and data in a module to get a singleton object.

If we really want a singleton class, we can consider doing this:

class Singleton(object):
 def foo(self):
 pass
singleton = Singleton()
Copy after login

Save the above code in the file mysingleton.py. When you want to use it, directly in Import the object in this file into other files. This object is the object of the singleton mode.

from mysingleton import singleton
Copy after login

Use the decorator

def Singleton(cls):
 _instance = {}
 def _singleton(*args, **kargs):
 if cls not in _instance:
 _instance[cls] = cls(*args, **kargs)
 return _instance[cls]
 return _singleton
@Singleton
class A(object):
 a = 1
 def __init__(self, x=0):
 self.x = x
a1 = A(2)
a2 = A(3)
Copy after login

Use the class

class Singleton(object):
 def __init__(self):
 pass
 @classmethod
 def instance(cls, *args, **kwargs):
 if not hasattr(Singleton, "_instance"):
 Singleton._instance = Singleton(*args, **kwargs)
 return Singleton._instance
Copy after login

Generally, everyone thinks that this completes the singleton mode, but there will be problems when using multi-threading:

class Singleton(object):
 def __init__(self):
 pass
 @classmethod
 def instance(cls, *args, **kwargs):
 if not hasattr(Singleton, "_instance"):
 Singleton._instance = Singleton(*args, **kwargs)
 return Singleton._instance
import threading
def task(arg):
 obj = Singleton.instance()
 print(obj)
for i in range(10):
 t = threading.Thread(target=task,args=[i,])
 t.start()
Copy after login

After the program is executed, the printed result is as follows:

<__main__.Singleton object at 0x02C933D0>
<__main__.Singleton object at 0x02C933D0>
<__main__.Singleton object at 0x02C933D0>
<__main__.Singleton object at 0x02C933D0>
<__main__.Singleton object at 0x02C933D0>
<__main__.Singleton object at 0x02C933D0>
<__main__.Singleton object at 0x02C933D0>
<__main__.Singleton object at 0x02C933D0>
<__main__.Singleton object at 0x02C933D0>
<__main__.Singleton object at 0x02C933D0>
Copy after login

See There is no problem, but it is because the execution speed is too fast. If there are some IO operations in the __init__ method, you will find the problem.

Below we simulate through time.sleep. We add the following code to the __init__ method above:

def __init__(self):
 import time
 time.sleep(1)
Copy after login

After re-executing the program, the results are as follows:

<__main__.Singleton object at 0x034A3410>
<__main__.Singleton object at 0x034BB990>
<__main__.Singleton object at 0x034BB910>
<__main__.Singleton object at 0x034ADED0>
<__main__.Singleton object at 0x034E6BD0>
<__main__.Singleton object at 0x034E6C10>
<__main__.Singleton object at 0x034E6B90>
<__main__.Singleton object at 0x034BBA30>
<__main__.Singleton object at 0x034F6B90>
<__main__.Singleton object at 0x034E6A90>
Copy after login

A problem occurred! Singletons created in the above manner cannot support multi-threading.

Solution: Lock! The unlocked part is executed concurrently, and the locked part is executed serially, which reduces the speed but ensures data security.

import time
import threading
class Singleton(object):
 _instance_lock = threading.Lock()
 def __init__(self):
 time.sleep(1)
 @classmethod
 def instance(cls, *args, **kwargs):
 with Singleton._instance_lock:
 if not hasattr(Singleton, "_instance"):
 Singleton._instance = Singleton(*args, **kwargs)
 return Singleton._instance
def task(arg):
 obj = Singleton.instance()
 print(obj)
for i in range(10):
 t = threading.Thread(target=task,args=[i,])
 t.start()
time.sleep(20)
obj = Singleton.instance()
print(obj)
Copy after login

The print result is as follows:

<__main__.Singleton object at 0x02D6B110>
<__main__.Singleton object at 0x02D6B110>
<__main__.Singleton object at 0x02D6B110>
<__main__.Singleton object at 0x02D6B110>
<__main__.Singleton object at 0x02D6B110>
<__main__.Singleton object at 0x02D6B110>
<__main__.Singleton object at 0x02D6B110>
<__main__.Singleton object at 0x02D6B110>
<__main__.Singleton object at 0x02D6B110>
<__main__.Singleton object at 0x02D6B110>
Copy after login

This is almost the same, but there is still a small problem, that is, when the program is executed, after time.sleep(20) is executed, the object is instantiated below , it is already in singleton mode.

But we still added a lock, which is not good. We will make some optimizations and change the intance method to the following:

@classmethod
def instance(cls, *args, **kwargs):
 if not hasattr(Singleton, "_instance"):
 with Singleton._instance_lock:
 if not hasattr(Singleton, "_instance"):
 Singleton._instance = Singleton(*args, **kwargs)
 return Singleton._instance
Copy after login

In this way, one can support multiple threads The singleton mode is completed.

import time
import threading
class Singleton(object):
 _instance_lock = threading.Lock()
 def __init__(self):
 time.sleep(1)
 @classmethod
 def instance(cls, *args, **kwargs):
 if not hasattr(Singleton, "_instance"):
 with Singleton._instance_lock:
 if not hasattr(Singleton, "_instance"):
 Singleton._instance = Singleton(*args, **kwargs)
 return Singleton._instance
def task(arg):
 obj = Singleton.instance()
 print(obj)
for i in range(10):
 t = threading.Thread(target=task,args=[i,])
 t.start()
time.sleep(20)
obj = Singleton.instance()
print(obj)
Copy after login

The singleton mode implemented in this way has restrictions on use. Later instantiation must be through obj = Singleton.instance()

If obj = Singleton() is used , what you get in this way is not a singleton.

Based on the __new__ method

Through the above example, we can know that when we implement a singleton, we need to add a lock internally to ensure thread safety.

We know that when we instantiate an object, we first execute the __new__ method of the class (when we don’t write it, object.__new__ is called by default), instantiate the object; and then execute the class The __init__ method initializes this object, so we can implement the singleton mode based on this.

import threading
class Singleton(object):
 _instance_lock = threading.Lock()
 def __init__(self):
 pass
 def __new__(cls, *args, **kwargs):
 if not hasattr(Singleton, "_instance"):
 with Singleton._instance_lock:
 if not hasattr(Singleton, "_instance"):
 Singleton._instance = object.__new__(cls)
 return Singleton._instance
obj1 = Singleton()
obj2 = Singleton()
print(obj1,obj2)
def task(arg):
 obj = Singleton()
 print(obj)
for i in range(10):
 t = threading.Thread(target=task,args=[i,])
 t.start()
Copy after login

The print result is as follows:

<__main__.Singleton object at 0x038B33D0> <__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
Copy after login

Using this singleton mode, when instantiating the object in the future, the method of instantiating the object is the same as usual obj = Singleton().

Implemented based on metaclass method

Related knowledge:

  1. Classes are created by type. When creating a class, type’s __init__ The method is automatically executed, and the class() executes the __call__ method of type (the __new__ method of the class, the __init__ method of the class).
  2. Objects are created by classes. When creating an object, the __init__ method of the class is automatically executed, and the object() executes the __call__ method of the class.
例子:
class Foo:
 def __init__(self):
 pass
 def __call__(self, *args, **kwargs):
 pass
obj = Foo()
# 执行type的 __call__ 方法,调用 Foo类(是type的对象)的 __new__方法,用于创建对象,然后调用 Foo类(是type的对象)的 __init__方法,用于对对象初始化。
obj()# 执行Foo的 __call__ 方法
Copy after login

Use of metaclass:

class SingletonType(type):
 def __init__(self,*args,**kwargs):
 super(SingletonType,self).__init__(*args,**kwargs)
 def __call__(cls, *args, **kwargs): # 这里的cls,即Foo类
 print('cls',cls)
 obj = cls.__new__(cls,*args, **kwargs)
 cls.__init__(obj,*args, **kwargs) # Foo.__init__(obj)
 return obj
class Foo(metaclass=SingletonType): # 指定创建Foo的type为SingletonType
 def __init__(self,name):
 self.name = name
 def __new__(cls, *args, **kwargs):
 return object.__new__(cls)
obj = Foo('xx')
Copy after login

Implementing singleton mode:

import threading
class SingletonType(type):
 _instance_lock = threading.Lock()
 def __call__(cls, *args, **kwargs):
 if not hasattr(cls, "_instance"):
 with SingletonType._instance_lock:
 if not hasattr(cls, "_instance"):
 cls._instance = super(SingletonType,cls).__call__(*args, **kwargs)
 return cls._instance
class Foo(metaclass=SingletonType):
 def __init__(self,name):
 self.name = name
obj1 = Foo('name')
obj2 = Foo('name')
print(obj1,obj2)
Copy after login

The above is the detailed content of Five ways to implement singleton mode in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:51cto.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template