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# Make coding more python3-ish 5from __future__ import (absolute_import, division, print_function) 6__metaclass__ = type 7 8from threading import RLock 9 10 11class Singleton(type): 12 """Metaclass for classes that wish to implement Singleton 13 functionality. If an instance of the class exists, it's returned, 14 otherwise a single instance is instantiated and returned. 15 """ 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 30