Skip to content

Instantly share code, notes, and snippets.

@luluco250
Last active January 24, 2023 15:57
Show Gist options
  • Save luluco250/180c94a5654567c3cdd393c02b712643 to your computer and use it in GitHub Desktop.
Save luluco250/180c94a5654567c3cdd393c02b712643 to your computer and use it in GitHub Desktop.
Python dump non-printable object as yaml (not guaranteed to be production ready, just a personal utility).
'''
obj_to_yaml() can print an object to a Yaml-like string.
This is useful to inspect complex objects in a friendlier manner.
'''
from typing import Any
def is_non_printable(obj: Any) -> bool:
return hasattr(obj, '__dict__')
def is_static(obj: Any, member_name: str) -> bool:
return hasattr(type(obj), member_name)
def obj_to_yaml(name: str, obj: Any, max_depth=2, indent=1) -> str:
class_name = obj.__class__.__name__
lines = [f'{" " * (indent - 1)}{name}: # {class_name}']
if max_depth <= 0:
return lines[0]
for prop in dir(obj):
if prop.startswith('_') or is_static(obj, prop):
continue
try:
value = getattr(obj, prop)
except Exception:
continue
if callable(value):
continue
elif is_non_printable(value):
lines.append(obj_to_yaml(prop, value, max_depth - 1, indent + 1))
continue
elif isinstance(value, tuple):
text = f'[{", ".join(value)}]'
elif isinstance(value, (str, bytes)):
text = f"'{value}'"
elif value is None:
text = 'null'
elif isinstance(value, bool):
text = 'true' if value else 'false'
else:
text = str(value)
lines.append(f'{" " * indent}{prop}: {text}')
return '\n'.join(lines)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment