Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanThomson/d9f7bdf4a8108ea7185d09428dda6d88 to your computer and use it in GitHub Desktop.
Save DanThomson/d9f7bdf4a8108ea7185d09428dda6d88 to your computer and use it in GitHub Desktop.
Generic __repr__ for sqlalchemy models
@classmethod
def _repr_template(cls):
"""
Creates a class specific template for __repr__
"""
beginning, middle, end = ('{}(', "{}={{{}}}", ')')
table = cls.__table__
primary_fields = table.primary_key.columns_autoinc_first
primary_field_names = [column.name for column in primary_fields]
filter_primary = lambda key: key not in primary_field_names
other_field_names = filter(filter_primary, table.columns.keys())
field_names = primary_field_names + other_field_names
middle = ', '.join((middle.format(name, name) for name in field_names))
return beginning + middle + end
def __repr__(self):
keys_to_repr = {k: v.__repr__() for k, v in self.__dict__.items()}
class_name = self.__class__.__name__
template_string = self._repr_template()
return template_string.format(class_name, **keys_to_repr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment