Home >Backend Development >Python Tutorial >What is the best way to implement a singleton in Python?

What is the best way to implement a singleton in Python?

Susan Sarandon
Susan SarandonOriginal
2024-12-17 16:07:09295browse

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!

Statement:
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