def to_dict(
obj: Union[int, float, str, bool, dict[Any, Any], list[Any], tuple[Any, ...], Any],
exclude: tuple[str, ...] = (),
no_recursive: tuple[Any, ...] = (),
) -> Any:
"""Convert object to dictionary.
Args:
obj (Union[int, float, str, bool, dict[Any, Any], list[Any], tuple[Any, ...], Any]): Object to convert
exclude (tuple[str, ...], optional): Keys to exclude. Defaults to ().
no_recursive (tuple[Any, ...], optional): Types to exclude from recursive conversion. Defaults to ().
"""
if isinstance(obj, (int, float, str, bool)):
return obj
elif isinstance(obj, (Path, PurePath)):
return str(obj)
elif callable(obj):
return inspect.getsource(obj).strip()
elif isinstance(obj, dict):
return {
str(k): to_dict(str(v)) if isinstance(v, no_recursive) else to_dict(v, exclude, no_recursive)
for k, v in obj.items()
if k not in exclude
}
elif isinstance(obj, (list, tuple)):
return [to_dict(str(v)) if isinstance(v, no_recursive) else to_dict(v, exclude, no_recursive) for v in obj]
elif hasattr(obj, "__dict__"):
return {
str(k): to_dict(str(v)) if isinstance(v, no_recursive) else to_dict(v, exclude, no_recursive)
for k, v in vars(obj).items()
if k not in exclude
}
else:
return obj