[Python-ideas] automation of __repr__/__str__ for all the common simple cases

Ronny Pfannschmidt Ronny.Pfannschmidt at gmx.de
Thu Feb 16 07:54:06 CET 2012


On 02/16/2012 12:43 AM, Steven D'Aprano wrote:
> Ronny Pfannschmidt wrote:
>> Hi,
>>
>> in my experience for many cases, __repr__ and __str__ can be
>> unconditionally be represented as simple string formatting operation,
>
> In my experience, not so much.
>
>
>> so i would propose to add a extension to support simply declaring them
>> in the form of newstyle format strings
>
> Declare them how? What is your proposed API for using this new
> functionality? Before proposing an implementation, you should propose an
> interface.
>
>
>> 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)})
>
>
> I don't think you need this just to get a generic "instance at id"
> string. If you inherit from object (and remember that all classes
> inherit from object in Python 3) you get this for free:
>
>  >>> class K(object):
> ... pass
> ...
>  >>> k = K()
>  >>> str(k)
> '<__main__.K object at 0xb746068c>'
>
>
>

seems like you completely missed that class-level attributes can easily 
be redefined by subclasses

like

class User(SimpleReprMixin):
   _repr_ = "<User {name!r}>"
   ...

the implementation and the interface is pretty simple and straightforward



More information about the Python-ideas mailing list