Skip to content

Instantly share code, notes, and snippets.

@piroux
Created December 5, 2018 11:05
Show Gist options
  • Save piroux/b91fb68bd40aa486fb77c8ea876edf39 to your computer and use it in GitHub Desktop.
Save piroux/b91fb68bd40aa486fb77c8ea876edf39 to your computer and use it in GitHub Desktop.
NameMixin For SqlAlchemy
from sqlalchemy import inspect
def to_str(x, charset='utf8', errors='strict'):
if x is None or isinstance(x, str):
return x
if isinstance(x, unicode):
return x.encode(charset, errors)
return str(x)
class NameMixin(object):
def __str__(self):
identity = inspect(self).identity
if identity is None:
pk = "(transient {})".format(id(self))
else:
pk = ', '.join(to_str(value) for value in identity)
return '<{} [{}] {}>'.format(type(self).__name__, pk, to_str(self.name))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment