Skip to content

Instantly share code, notes, and snippets.

@dotchetter
Last active May 6, 2023 14:27
Show Gist options
  • Save dotchetter/e52cc8fc2def24fbe51a4692a27dc807 to your computer and use it in GitHub Desktop.
Save dotchetter/e52cc8fc2def24fbe51a4692a27dc807 to your computer and use it in GitHub Desktop.
Simple mixin class in Python extracted from my framework Pyttman, mitigating the need to override __repr__ in convoluted ways over and over.
class PrettyReprMixin:
"""
Mixin providing a common interface for
__repr__ methods which represents classes
in a very readable way.
- How to use:
Define which fields to include when printing the
class or calling repr(some_object), by adding their
names to the '__repr_fields__' tuple.
class User(PrettyReprMixin):
__repr_fields__ = ("first_name", "last_name", "property_attrib")
def __init__(self, first_name, last_name)
self.first_name = first_name
self.last_name = last_name
@property
def property_attrib(self) -> str:
return "Something dynamic, just add my name in __repr_fields__"
This is just too handy!
"""
__repr_fields__ = ()
def __repr__(self):
name = self.__class__.__name__
attrs = [f"{i}={getattr(self, str(i))}" for i in self.__repr_fields__]
return f"{name}({', '.join(attrs)})"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment