Home >Backend Development >Python Tutorial >What is 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".
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:
Disadvantages:
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:
Disadvantages:
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:
Disadvantages:
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:
Cons:
Singleton module singleton.py.
Pros:
Disadvantages:
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
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.
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".
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.
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!