python singleton

Solutions on MaxInterview for python singleton by the best coders in the world

showing results for - "python singleton"
Emilio
12 Mar 2018
1@Singleton
2class Foo:
3   def __init__(self):
4       print 'Foo created'
5
6f = Foo() # Error, this isn't how you get the instance of a singleton
7
8f = Foo.instance() # Good. Being explicit is in line with the Python Zen
9g = Foo.instance() # Returns already created instance
10
11print f is g # True
12
David
12 Aug 2017
1class Singleton:
2    """
3    A non-thread-safe helper class to ease implementing singletons.
4    This should be used as a decorator -- not a metaclass -- to the
5    class that should be a singleton.
6
7    The decorated class can define one `__init__` function that
8    takes only the `self` argument. Also, the decorated class cannot be
9    inherited from. Other than that, there are no restrictions that apply
10    to the decorated class.
11
12    To get the singleton instance, use the `instance` method. Trying
13    to use `__call__` will result in a `TypeError` being raised.
14
15    """
16
17    def __init__(self, decorated):
18        self._decorated = decorated
19
20    def instance(self):
21        """
22        Returns the singleton instance. Upon its first call, it creates a
23        new instance of the decorated class and calls its `__init__` method.
24        On all subsequent calls, the already created instance is returned.
25
26        """
27        try:
28            return self._instance
29        except AttributeError:
30            self._instance = self._decorated()
31            return self._instance
32
33    def __call__(self):
34        raise TypeError('Singletons must be accessed through `instance()`.')
35
36    def __instancecheck__(self, inst):
37        return isinstance(inst, self._decorated)
38