Debian Codegraph @

lib/ansible/utils/singleton.py

raw
1 # Copyright (c) 2017 Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 from __future__ import annotations
5
6 from threading import RLock
7
8
9 class Singleton(type):
10 """Metaclass for classes that wish to implement Singleton
11 functionality. If an instance of the class exists, it's returned,
12 otherwise a single instance is instantiated and returned.
13 """
14
15 # FIXME: object identity/singleton-ness does not appear to survive pickle roundtrip (eg, copy.copy, copy.deepcopy), implement __reduce_ex__ and __copy__?
16 def __init__(cls, name, bases, dct):
17 super(Singleton, cls).__init__(name, bases, dct)
18 cls.__instance = None
19 cls.__rlock = RLock()
20
21 def __call__(cls, *args, **kw):
22 if cls.__instance is not None:
23 return cls.__instance
24
25 with cls.__rlock:
26 if cls.__instance is None:
27 cls.__instance = super(Singleton, cls).__call__(*args, **kw)
28
29 return cls.__instance