Skip to content

Instantly share code, notes, and snippets.

@tmichel
Created July 21, 2014 11:22
Show Gist options
  • Save tmichel/df0762681d1d879b0aa8 to your computer and use it in GitHub Desktop.
Save tmichel/df0762681d1d879b0aa8 to your computer and use it in GitHub Desktop.
sqlalchemy generic __repr__
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.properties import ColumnProperty
class RepresentableBase(object):
def __repr__(self):
prop = filter(lambda p: isinstance(p, ColumnProperty), self.__mapper__.iterate_properties)
keys = [p.key for p in prop]
prop_values = dict(zip(keys, [getattr(self, k) for k in keys]))
values = ", ".join(sorted(map(lambda (k,v): '{}={}'.format(k, v), prop_values.iteritems())))
return "<{} ({})>".format(self.__class__.__name__, values)
Base = declarative_base(cls=RepresentableBase)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment