python-mylib/mylib/__init__.py

87 lines
2.7 KiB
Python

""" Some really common helper functions """
#
# Pretty formatting helpers
#
def increment_prefix(prefix):
"""Increment the given prefix with two spaces"""
return f'{prefix if prefix else " "} '
def pretty_format_value(value, encoding="utf8", prefix=None):
"""Returned pretty formatted value to display"""
if isinstance(value, dict):
return pretty_format_dict(value, encoding=encoding, prefix=prefix)
if isinstance(value, list):
return pretty_format_list(value, encoding=encoding, prefix=prefix)
if isinstance(value, bytes):
return f"'{value.decode(encoding, errors='replace')}'"
if isinstance(value, str):
return f"'{value}'"
if value is None:
return "None"
return f"{value} ({type(value)})"
def pretty_format_value_in_list(value, encoding="utf8", prefix=None):
"""
Returned pretty formatted value to display in list
That method will prefix value with line return and incremented prefix
if pretty formatted value contains line return.
"""
prefix = prefix if prefix else ""
value = pretty_format_value(value, encoding, prefix)
if "\n" in value:
inc_prefix = increment_prefix(prefix)
value = "\n" + "\n".join([inc_prefix + line for line in value.split("\n")])
return value
def pretty_format_dict(value, encoding="utf8", prefix=None):
"""Returned pretty formatted dict to display"""
prefix = prefix if prefix else ""
result = []
for key in sorted(value.keys()):
result.append(
f"{prefix}- {key} : "
+ pretty_format_value_in_list(value[key], encoding=encoding, prefix=prefix)
)
return "\n".join(result)
def pretty_format_list(row, encoding="utf8", prefix=None):
"""Returned pretty formatted list to display"""
prefix = prefix if prefix else ""
result = []
for idx, values in enumerate(row):
result.append(
f"{prefix}- #{idx} : "
+ pretty_format_value_in_list(values, encoding=encoding, prefix=prefix)
)
return "\n".join(result)
def pretty_format_timedelta(timedelta):
"""Format timedelta object"""
seconds = int(timedelta.total_seconds())
if seconds < 1:
return "less than one second"
periods = [
("year", 60 * 60 * 24 * 365),
("month", 60 * 60 * 24 * 30),
("day", 60 * 60 * 24),
("hour", 60 * 60),
("minute", 60),
("second", 1),
]
strings = []
for period_name, period_seconds in periods:
if seconds >= period_seconds:
period_value, seconds = divmod(seconds, period_seconds)
strings.append(f'{period_value} {period_name}{"s" if period_value > 1 else ""}')
return ", ".join(strings)