Skip to content

Instantly share code, notes, and snippets.

@eirnym
Forked from exhuma/representable_base.py
Last active August 29, 2015 14:18
Show Gist options
  • Save eirnym/41b8707d002aad2313b4 to your computer and use it in GitHub Desktop.
Save eirnym/41b8707d002aad2313b4 to your computer and use it in GitHub Desktop.
this representable base adds generatable __str__ and __repr__
# based on: https://gist.github.com/exhuma/5935162#file-representable_base-py
class RepresentableBase(object):
""" Add automatic __repr__ and __str__ to SQLAlchemy ORM models
"""
def _repr_worker(self, attribute):
mapper = object_mapper(self)
items = [(p.key, getattr(self, p.key))
for p in (
mapper.get_property_by_column(c)
for c in getattr(mapper, attribute))]
return "{0}({1})".format(
self.__class__.__name__,
', '.join(['{0}={1!r}'.format(*attr_pair) for attr_pair in items]))
def __repr__(self):
'''This will represent ``self`` as::
ClassName(pkey_1='value1', pkey_2='value2')
where ``pkey_1..pkey_n`` are the primary key columns
of the mapped table
'''
return self._repr_worker('primary_key')
def __str__(self):
'''This will represent ``self`` as::
ClassName(column_1='value1', column_2='value2')
where ``column_1..column_n`` are the all columns
of the mapped table
'''
return self._repr_worker('columns')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment