Created
May 10, 2017 14:43
-
-
Save DanThomson/d9f7bdf4a8108ea7185d09428dda6d88 to your computer and use it in GitHub Desktop.
Generic __repr__ for sqlalchemy models
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
@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