[Python-ideas] automation of __repr__/__str__ for all the common simple cases
Ronny Pfannschmidt
Ronny.Pfannschmidt at gmx.de
Wed Feb 15 15:32:10 CET 2012
Hi,
in my experience for many cases, __repr__ and __str__ can be
unconditionally be represented as simple string formatting operation,
so i would propose to add a extension to support simply declaring them
in the form of newstyle format strings
a basic implementation for __repr__ could look like:
class SelfFormatter(string.Formatter):
def __init__(self, obj):
self.__obj = obj
string.Formatter.__init__(self)
def get_value(self, key, args, kwargs):
if isinstance(key, str) and hasattr(self.__obj, key):
return getattr(self.__obj, key)
return Formatter.get_value(self, key, args, kwargs)
class SimpleReprMixing(object):
_repr_ = '<{__class__.__name__} at 0x{__id__!x}>'
def __repr__(self):
formatter = SelfFormatter(self)
return formatter.vformat(self._repr_, (), {'__id__':id(self)})
-- Ronny Pfannschmidt
More information about the Python-ideas
mailing list