Skip to content

Instantly share code, notes, and snippets.

@exhuma
Last active December 19, 2015 09:39
Show Gist options
  • Save exhuma/5935162 to your computer and use it in GitHub Desktop.
Save exhuma/5935162 to your computer and use it in GitHub Desktop.
class RepresentableBase(object):
"""
This class can be used by ``declarative_base``, to add an automatic
``__repr__`` method to *all* subclasses of ``Base``. This ``__repr__`` will
represent values as::
ClassName(pkey_1=value_1, pkey_2=value_2, ..., pkey_n=value_n)
where ``pkey_1..pkey_n`` are the primary key columns of the mapped table
with the corresponding values.
"""
def __repr__(self):
mapper = object_mapper(self)
items = [(p.key, getattr(self, p.key))
for p in [
mapper.get_property_by_column(c) for c in mapper.primary_key]]
return "{0}({1})".format(
self.__class__.__name__,
', '.join(['{0}={1!r}'.format(*_) for _ in items]))
Base = declarative_base(cls=RepresentableBase)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment