format_dict(d: Mapping[str, Any], level: int = 0, indent_width: int = 2) -> str
Format a dict in a human-readable format.
Simple values are printed as-is, lists are printed as comma-separated values,
and dicts are recursively formatted with keys as section headers.
Source code in src/jobq/utils/helpers.py
| def format_dict(d: Mapping[str, Any], level: int = 0, indent_width: int = 2) -> str:
"""Format a dict in a human-readable format.
Simple values are printed as-is, lists are printed as comma-separated values,
and dicts are recursively formatted with keys as section headers.
"""
def format_value(value: Any, level: int) -> str:
if isinstance(value, Mapping):
return format_dict(value, level + 1)
elif isinstance(value, list):
return "\n".join(
" " * ((level + 1) * indent_width)
+ "- "
+ format_value(item, level + 1).strip()
for item in value
)
else:
strval = str(value).strip()
if "\n" in strval:
return "\n" + textwrap.indent(
strval, prefix=" " * (level * indent_width)
)
else:
return strval
indent = " " * (level * indent_width)
formatted_items = []
for key, value in d.items():
formatted_value = format_value(value, level) or f"{indent} <empty>"
header = f"{indent}{to_human(key)}"
if isinstance(value, list | Mapping):
formatted_items.append(f"{header}:\n{formatted_value}\n")
else:
formatted_items.append(f"{header}: {formatted_value}")
return "\n".join(formatted_items)
|