What is the best way to implement a singleton in Python?
The best way to implement a singleton in Python
Although the advantages and disadvantages of the singleton design pattern are not the focus of this article, this article will explore how to implement the singleton in Python in the best possible way. Implement this pattern in a Pythonic way. Here, "most Pythonic" means following the "principle of least surprise".
Implementation method
Method 1: Decorator
def singleton(class_): instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance @singleton class MyClass(BaseClass): pass
Advantages:
- The decorator has addition sex, more intuitive than multiple inheritance.
Disadvantages:
- The object created using MyClass() is a real singleton object, but MyClass itself is a function, not a class, so class methods cannot be called.
Method 2: Base class
class Singleton(object): _instance = None def __new__(class_, *args, **kwargs): if not isinstance(class_._instance, class_): class_._instance = object.__new__(class_, *args, **kwargs) return class_._instance class MyClass(Singleton, BaseClass): pass
Advantages:
- It is a real class.
Disadvantages:
- Multiple inheritance, unpleasant. When inheriting from a second base class, __new__ may be overridden.
Method 3: Metaclass
class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] # Python2 class MyClass(BaseClass): __metaclass__ = Singleton # Python3 class MyClass(BaseClass, metaclass=Singleton): pass
Advantages:
- It is a real class.
- Inheritance is automatically covered.
- Use __metaclass__ correctly (and make me understand it).
Disadvantages:
- No disadvantages.
Method 4: Return the decorator of the class with the same name
def singleton(class_): class class_w(class_): _instance = None def __new__(class_, *args, **kwargs): if class_w._instance is None: class_w._instance = super(class_w, class_).__new__(class_, *args, **kwargs) class_w._instance._sealed = False return class_w._instance def __init__(self, *args, **kwargs): if self._sealed: return super(class_w, self).__init__(*args, **kwargs) self._sealed = True class_w.__name__ = class_.__name__ return class_w @singleton class MyClass(BaseClass): pass
Advantages:
- It is a real class.
- Inheritance is automatically covered.
Cons:
- Is there an overhead in creating two classes for each class that you want to become a singleton? While this works fine in my case, I'm worried it might not scale. What is the purpose of the
- _sealed attribute?
- You cannot use super() to call methods with the same name in a base class because they would be recursive. This means that __new__ cannot be customized, nor can a class that requires calling __init__ be subclassed.
Method 5: Module
Singleton module singleton.py.
Pros:
- Simple is better than complex.
Disadvantages:
- Not deferred instantiation.
Recommended Method
I recommend using Method 2, but it is better to use metaclasses instead of base classes. Here is an example implementation:
class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class Logger(object): __metaclass__ = Singleton
Or in Python3:
class Logger(metaclass=Singleton): pass
If you want __init__ to run every time a class is called, add the following code to Singleton.__call__ In the if statement:
def singleton(class_): instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance @singleton class MyClass(BaseClass): pass
The role of metaclass
A metaclass is a class of classes, that is, a class is an instance of its metaclass. The metaclass of an object in Python can be found via type(obj). Normal new classes are of type type. The above Logger will be of type class 'your_module.Singleton' just like the (only) instance of Logger will be of type class 'your_module.Logger' . When a logger is called using Logger(), Python first asks the Logger's metaclass Singleton what it should do, allowing preemptive instance creation. The process is similar to how Python asks a class what it should do with its attributes by calling __getattr__, and you reference its attributes by doing myclass.attribute.
Metaclasses essentially determine what the calling class means and how to implement that meaning. See e.g. http://code.activestate.com/recipes/498149/ which uses metaclasses to essentially recreate C-style structures in Python. Discussion Thread [What are the specific use cases for metaclasses? ](https://codereview.stackexchange.com/questions/82786/what-are-some-concrete-use-cases-for-metaclasses) also provides some examples, which are generally related to declarative programming, especially in ORM used in.
In this case, if you use your Method 2 and a subclass defines a __new__ method, it will be executed every time SubClassOfSingleton() is called, because It is responsible for calling methods that return stored instances. With metaclasses, it is only executed once, when the unique instance is created. You need to customize the definition of the calling class, which is determined by its type.
In general, it makes sense to use metaclasses to implement singletons. A singleton is special because its instance is created only once, while a metaclass is a custom implementation of a created class that makes it behave differently than a normal class. Using metaclasses gives you more control when you would otherwise need to customize your singleton class definition.
Of course
Your singleton does not need multiple inheritance (because the metaclass is not a base class), but for inheritance to create a subclass of a class, you need to make sure the singleton class is the first/ The leftmost metaclass redefines __call__. This is unlikely to be a problem. The instance dictionary is not in the instance's namespace, so it cannot be accidentally overwritten.
You will also hear that the singleton pattern violates the "single responsibility principle", which means that each class should only do one thing. This way, you don't have to worry about breaking one thing the code does when you need to change another code because they are independent and encapsulated. The metaclass implementation passes this test. Metaclasses are responsible for enforcing the pattern, creating classes and subclasses that don't need to be aware that they are singletons. Method 1 fails this test, as you pointed out with "MyClass itself is a function, not a class, so class methods cannot be called".
Python 2 and 3 compatible versions
Writing code in Python 2 and 3 requires a slightly more complicated scheme. Since metaclasses are usually subclasses of the type class, you can use a metaclass to dynamically create an intermediary base class with it as a metaclass at runtime, and then use that base class as the base class for a public singleton base class. This is easier said than done, as follows:
def singleton(class_): instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance @singleton class MyClass(BaseClass): pass
One irony of this approach is that it uses subclassing to implement metaclasses. One possible advantage is that, unlike a pure metaclass, isinstance(inst, Singleton) will return True.
Correction
Regarding another topic, you may have noticed, but the base class implementation in your original post was wrong. To reference _instances within a class, you need to use super(), or a static method of the class method, since the actual class has not yet been created at the time of the call. All of this holds true for metaclass implementations as well.
class Singleton(object): _instance = None def __new__(class_, *args, **kwargs): if not isinstance(class_._instance, class_): class_._instance = object.__new__(class_, *args, **kwargs) return class_._instance class MyClass(Singleton, BaseClass): pass
The above is the detailed content of What is the best way to implement a singleton in Python?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.
