Skip to content

Instantly share code, notes, and snippets.

@miracle2k
Last active August 29, 2015 14:13
Show Gist options
  • Save miracle2k/7105912ca21028f64e52 to your computer and use it in GitHub Desktop.
Save miracle2k/7105912ca21028f64e52 to your computer and use it in GitHub Desktop.
Automagic __repr__ for SQLAlchemy entities with primary key columns with Declarative Base.
# Adapted from http://foobar.lu/wp/2013/07/05/automagic-__repr__-for-sqlalchemy-entities-with-primary-key-columns-with-declarative-base/
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]))
Model = declarative_base(cls=RepresentableBase)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment