Last active
February 8, 2025 14:05
-
-
Save nazar-khimin/1117ccc5a18954bf6665771880452b8d to your computer and use it in GitHub Desktop.
Python pretty print repr generator
This file contains 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 generate_repr(fields=None): | |
def decorator(cls): | |
def __repr__(self): | |
repr_str = f'{cls.__name__}(' | |
attributes = [] | |
for attr, value in self.__dict__.items(): | |
if fields and attr in fields: | |
field_name = fields[attr] | |
if isinstance(value, list) and value and hasattr(value[0], field_name): | |
value = [getattr(item, field_name) for item in value] | |
elif hasattr(value, field_name): | |
value = getattr(value, field_name) | |
attributes.append(f'{attr}={value!r}') | |
repr_str += ", ".join(attributes) | |
repr_str += ")" | |
return repr_str | |
cls.__repr__ = __repr__ | |
return cls | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment