mirror of
https://github.com/ansible-collections/community.general.git
synced 2025-05-03 07:41:30 -07:00
Add a Singleton metaclass, use it with Display (#48935)
* Add a Singleton class, use it with Display * update six import * Move remaining failes to display singleton * Fix rebase issues * Singleton improvements * Add code-smell for 'from __main__ import display'. ci_complete * s/self/cls/g * Add docs for no-main-display * Address linting issues * Add changelog fragment. ci_complete * Implement reentrant lock for class instantiation in Singleton * Add Display singleton porting guide
This commit is contained in:
parent
54a2f21f93
commit
9773a1f289
149 changed files with 407 additions and 766 deletions
29
lib/ansible/utils/singleton.py
Normal file
29
lib/ansible/utils/singleton.py
Normal file
|
@ -0,0 +1,29 @@
|
|||
# Copyright (c) 2017 Ansible Project
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
# Make coding more python3-ish
|
||||
from __future__ import (absolute_import, division, print_function)
|
||||
__metaclass__ = type
|
||||
|
||||
from threading import RLock
|
||||
|
||||
|
||||
class Singleton(type):
|
||||
"""Metaclass for classes that wish to implement Singleton
|
||||
functionality. If an instance of the class exists, it's returned,
|
||||
otherwise a single instance is instantiated and returned.
|
||||
"""
|
||||
def __init__(cls, name, bases, dct):
|
||||
super(Singleton, cls).__init__(name, bases, dct)
|
||||
cls.__instance = None
|
||||
cls.__rlock = RLock()
|
||||
|
||||
def __call__(cls, *args, **kw):
|
||||
if cls.__instance is not None:
|
||||
return cls.__instance
|
||||
|
||||
with cls.__rlock:
|
||||
if cls.__instance is None:
|
||||
cls.__instance = super(Singleton, cls).__call__(*args, **kw)
|
||||
|
||||
return cls.__instance
|
Loading…
Add table
Add a link
Reference in a new issue