From afdb1430a69c49103ebdf7031c8e93536ec5b166 Mon Sep 17 00:00:00 2001 From: Benjamin Renard Date: Thu, 18 Nov 2021 19:56:51 +0100 Subject: [PATCH] Fix/improve pretty_format* helpers --- mylib/__init__.py | 64 ++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 55 insertions(+), 9 deletions(-) diff --git a/mylib/__init__.py b/mylib/__init__.py index 035caa9..557fde6 100644 --- a/mylib/__init__.py +++ b/mylib/__init__.py @@ -5,30 +5,76 @@ # # Pretty formating helpers # -def pretty_format_value(value, encoding='utf8'): + + +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) + return pretty_format_dict(value, encoding=encoding, prefix=prefix) if isinstance(value, list): - return ",".join([pretty_format_value(x) for x in value]) + 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 - return str(value) + if value is None: + return "None" + return "%s (%s)" % (str(value), type(value)) -def pretty_format_dict(attrs): +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 attr in sorted(attrs.keys()): - result.append(" - %s : %s" % (attr, pretty_format_value(attrs[attr]))) + 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): +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" % (idx, pretty_format_value(values))) + result.append( + "%s- #%s : %s" % ( + prefix, idx, + pretty_format_value_in_list( + values, + encoding=encoding, + prefix=prefix + ) + ) + ) return "\n".join(result)