""" Some really common helper functions """ # # Pretty formating 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 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 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 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( 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 formated 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)