2023-07-28 18:45:18 +00:00
|
|
|
import os
|
|
|
|
import sys
|
|
|
|
|
2024-01-19 02:21:37 +00:00
|
|
|
import sys
|
|
|
|
from typing import Any, Dict
|
2024-01-15 15:52:10 +00:00
|
|
|
|
2024-02-02 17:05:46 +00:00
|
|
|
class NullDevice():
|
|
|
|
def write(self, s):
|
|
|
|
pass
|
2023-07-28 18:45:18 +00:00
|
|
|
|
|
|
|
class suppress_stdout_stderr(object):
|
2023-11-02 19:30:55 +00:00
|
|
|
# NOTE: these must be "saved" here to avoid exceptions when using
|
|
|
|
# this context manager inside of a __del__ method
|
|
|
|
sys = sys
|
|
|
|
os = os
|
|
|
|
|
2023-11-03 17:02:15 +00:00
|
|
|
def __init__(self, disable: bool = True):
|
|
|
|
self.disable = disable
|
|
|
|
|
2023-07-28 18:45:18 +00:00
|
|
|
# Oddly enough this works better than the contextlib version
|
|
|
|
def __enter__(self):
|
2023-11-03 17:02:15 +00:00
|
|
|
if self.disable:
|
|
|
|
return self
|
2023-11-02 19:30:55 +00:00
|
|
|
self.old_stdout = self.sys.stdout
|
|
|
|
self.old_stderr = self.sys.stderr
|
2023-07-28 18:45:18 +00:00
|
|
|
|
2024-02-02 17:05:46 +00:00
|
|
|
self.sys.stdout = NullDevice()
|
|
|
|
self.sys.stderr = NullDevice()
|
2023-07-28 18:45:18 +00:00
|
|
|
return self
|
|
|
|
|
|
|
|
def __exit__(self, *_):
|
2023-11-03 17:02:15 +00:00
|
|
|
if self.disable:
|
|
|
|
return
|
2024-02-02 17:05:46 +00:00
|
|
|
|
|
|
|
self.sys.stdout = self.old_stdout
|
|
|
|
self.sys.stderr = self.old_stderr
|
2024-01-19 02:21:37 +00:00
|
|
|
|
|
|
|
|
|
|
|
class MetaSingleton(type):
|
|
|
|
"""
|
|
|
|
Metaclass for implementing the Singleton pattern.
|
|
|
|
"""
|
|
|
|
|
|
|
|
_instances: Dict[type, Any] = {}
|
|
|
|
|
|
|
|
def __call__(cls, *args: Any, **kwargs: Any) -> Any:
|
|
|
|
if cls not in cls._instances:
|
|
|
|
cls._instances[cls] = super(MetaSingleton, cls).__call__(*args, **kwargs)
|
|
|
|
return cls._instances[cls]
|
|
|
|
|
|
|
|
|
|
|
|
class Singleton(object, metaclass=MetaSingleton):
|
|
|
|
"""
|
|
|
|
Base class for implementing the Singleton pattern.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
super(Singleton, self).__init__()
|