[Python-ideas] automation of __repr__/__str__ for all the common simple cases
Nathan Rice
nathan.alexander.rice at gmail.com
Wed Feb 15 16:34:45 CET 2012
I think that a generic __repr__ has been reinvented more times than I
can count. I don't think a generic __str__ is a good thing, as it is
supposed to be a pretty, semantically meaningful. I don't really see
anywhere in the standard library that such a feature would make sense
though. I feel like Python's standard library bloat actually makes
the good stuff harder to find, and a better approach would be to have
a minimal "core" standard library with a few "official" battery pack
style libs that are very prominently featured and available.
Since you might find this useful, here is my old __repr__ reciple
(which has several issues, but gets the job done for the most part):
def get_attributes(o):
attributes = [(a, getattr(o, a)) for a in
set(dir(o)).difference(dir(object)) if a[0] != "_"]
return {a[0]: a[1] for a in attributes if not callable(a[1])}
class ReprMixin(object):
def _format(self, v):
if isinstance(v, (basestring, date, time, datetime)):
v = "'%s'" % v
return v.encode("utf-8", errors="ignore")
else:
return v
def __repr__(self):
attribute_string = ", ".join("%s=%s" % (k[0],
self._format(k[1])) for k in get_attributes(self).items())
return "%s(%s)" % (type(self).__name__, attribute_string)
There is a similar recipes in SQL Alchemy, and I've seen them in a few
other popular libs that I can't remember off the top of my head.
Nathan
More information about the Python-ideas
mailing list