Skip to content

Instantly share code, notes, and snippets.

@MitchellKehn
Created April 6, 2021 13:43
Show Gist options
  • Save MitchellKehn/66742d9de7277b2fc24e346b81f1045a to your computer and use it in GitHub Desktop.
Save MitchellKehn/66742d9de7277b2fc24e346b81f1045a to your computer and use it in GitHub Desktop.
[SQLAlchemy ORM Pretty Repr] #orm #sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
# monkey-patch a nice __repr__ method onto the Base class.
def _niceRepr(self):
"""
Nicely format class name and column values.
Looks up the inheritance hierarchy for inherited columns and displays those too.
"""
attrs = []
for cls in [self.__class__] + list(self.__class__.__mro__):
if not hasattr(cls, "__table__"): break
for key in cls.__table__.columns.keys():
if key not in attrs:
attrs.append(key)
return "<{}: {}>".format(
self.__class__.__name__,
", ".join(["{}={}".format(attr, repr(getattr(self, attr))) for attr in attrs])
)
Base.__repr__ = _niceRepr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment