Last active
October 30, 2025 23:19
-
-
Save vlntnwbr/a47c4cece3fd7b70d0479d67e3552390 to your computer and use it in GitHub Desktop.
Method to create a string representation of any Python object that has a __dict__ attribute. The string formatting is inspired by the formatting of the Python dataclasses repr function. See docstring for details.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def repr_dict_obj( | |
| candidate: object, | |
| classname: str | None = None, | |
| attr_alt_reprs: ( | |
| None | dict[str, str | Callable[[object], str] | Literal["__exclude__"]] | |
| ) = None, | |
| ) -> str: | |
| """ | |
| Return a dataclass inspired repr string for given object. | |
| Args: | |
| candidate: the object to represent, must have __dict__ attribute | |
| classname: an alternative name to use for the object | |
| attr_alt_reprs: a mapping of attribute names to alternatives used for | |
| representing the attribute value. The different types allowed as | |
| alternative values influence the value representation. Using the | |
| literal `"__exclude__"` excludes the attribute from representation. | |
| Using a callable will pass the attribute value to that callable and | |
| use the returned string for the representation. Passing any string | |
| will use that string for the representation. | |
| Returns: | |
| str: representation the candidate (see examples) | |
| Raises: | |
| TypeError: if the given candidate has no __dict__ attribute | |
| Examples: | |
| .. code-block:: python | |
| >>> class MyObject: | |
| ... def __init__(self): | |
| ... self.hello = "there" | |
| ... self.general = "kenobi" | |
| ... self.bold = 1 | |
| ... | |
| >>> repr_dict_obj(MyObject()) | |
| "MyObject(hello='there', general='kenobi', bold=1)" | |
| >>> repr_dict_obj( | |
| ... MyObject(), | |
| ... classname="MyOtherObject" | |
| ... attr_alt_reprs={ | |
| ... "general": "skywalker", | |
| ... "bold": "__exclude__" | |
| ... } | |
| ... ) | |
| "MyOtherObject(hello='there', general='skywalker')" | |
| >>> repr_dict_obj( | |
| ... MyObject(), | |
| ... attr_alt_reprs={ | |
| ... "general": "skywalker", | |
| ... "bold": str | |
| ... } | |
| ... ) | |
| "MyObject(hello='there', general='skywalker', bold='1')" | |
| """ | |
| if not hasattr(candidate, "__dict__"): | |
| raise TypeError("given object doesn't have __dict__", candidate) | |
| attr_alt_reprs = attr_alt_reprs if attr_alt_reprs is not None else {} | |
| formatted_attributes: list[str] = [] | |
| for attribute, value in vars(candidate).items(): | |
| attribute_repr = f"{attribute}=" + "{!r}" | |
| match (alias := attr_alt_reprs.pop(attribute, None)): | |
| case "__exclude__": | |
| pass | |
| case None: | |
| formatted_attributes.append(attribute_repr.format(value)) | |
| case str(): | |
| formatted_attributes.append(attribute_repr.format(alias)) | |
| case _: | |
| formatted_attributes.append(attribute_repr.format(alias(value))) | |
| return f"{classname or candidate.__class__.__name__}({', '.join( | |
| formatted_attributes | |
| )})" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment