2020-03-01 17:42:29 +00:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
"""Global utility methods and classes."""
|
|
|
|
|
2023-10-16 10:11:13 +00:00
|
|
|
|
|
|
|
def strtobool(value):
|
|
|
|
"""Convert a string representation of truth to true or false."""
|
|
|
|
|
|
|
|
_map = {
|
|
|
|
"y": True,
|
|
|
|
"yes": True,
|
|
|
|
"t": True,
|
|
|
|
"true": True,
|
|
|
|
"on": True,
|
|
|
|
"1": True,
|
|
|
|
"n": False,
|
|
|
|
"no": False,
|
|
|
|
"f": False,
|
|
|
|
"false": False,
|
|
|
|
"off": False,
|
|
|
|
"0": False
|
|
|
|
}
|
|
|
|
|
|
|
|
try:
|
|
|
|
return _map[str(value).lower()]
|
|
|
|
except KeyError as err:
|
|
|
|
raise ValueError(f'"{value}" is not a valid bool value') from err
|
2020-03-01 17:42:29 +00:00
|
|
|
|
|
|
|
|
|
|
|
def to_bool(string):
|
|
|
|
return bool(strtobool(str(string)))
|
|
|
|
|
|
|
|
|
2020-03-08 14:39:22 +00:00
|
|
|
def dict_intersect(d1, d2):
|
|
|
|
return {
|
|
|
|
k: dict_intersect(d1[k], d2[k]) if isinstance(d1[k], dict) else d1[k]
|
|
|
|
for k in d1.keys() & d2.keys()
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2020-03-01 17:42:29 +00:00
|
|
|
class Singleton(type):
|
2020-03-06 21:39:32 +00:00
|
|
|
"""Singleton metaclass."""
|
|
|
|
|
2020-03-01 17:42:29 +00:00
|
|
|
_instances = {}
|
|
|
|
|
2023-02-12 13:46:35 +00:00
|
|
|
def __call__(cls, *args, **kwargs):
|
2020-03-06 21:39:32 +00:00
|
|
|
|
2020-03-01 17:42:29 +00:00
|
|
|
if cls not in cls._instances:
|
2023-02-12 13:46:35 +00:00
|
|
|
cls._instances[cls] = super().__call__(*args, **kwargs)
|
2020-03-01 17:42:29 +00:00
|
|
|
return cls._instances[cls]
|