python-mylib/mylib/__init__.py
2021-11-18 19:56:51 +01:00

80 lines
2.3 KiB
Python

# -*- coding: utf-8 -*-
""" Some really common helper functions """
#
# Pretty formating helpers
#
def increment_prefix(prefix):
return "%s " % prefix if prefix else " "
def pretty_format_value(value, encoding='utf8', prefix=None):
""" Returned pretty formated 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 "'%s'" % value.decode(encoding, errors='replace')
if isinstance(value, str):
return "'%s'" % value
if value is None:
return "None"
return "%s (%s)" % (str(value), type(value))
def pretty_format_value_in_list(value, encoding='utf8', prefix=None):
"""
Returned pretty formated value to display in list
That method will prefix value with line return and incremented prefix
if pretty formated 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 formated dict to display """
prefix = prefix if prefix else ""
result = []
for key in sorted(value.keys()):
result.append(
"%s- %s : %s" % (
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 formated list to display """
prefix = prefix if prefix else ""
result = []
for idx, values in enumerate(row):
result.append(
"%s- #%s : %s" % (
prefix, idx,
pretty_format_value_in_list(
values,
encoding=encoding,
prefix=prefix
)
)
)
return "\n".join(result)