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

Ronny Pfannschmidt Ronny.Pfannschmidt at gmx.de
Thu Feb 16 08:20:06 CET 2012


On 02/16/2012 08:13 AM, Nick Coghlan wrote:
> On Thu, Feb 16, 2012 at 4:54 PM, Ronny Pfannschmidt
> <Ronny.Pfannschmidt at gmx.de>  wrote:
>> the implementation and the interface is pretty simple and straightforward
>
> However, the question is whether it's simple and straightforward
> enough to be worth standardising.
>
> There are a few common patterns that recur in repr implementations:
>
> -<type(obj)&  id(obj)>  based (the object.__repr__ default)
>
> - cls(arg1, arg2...) positional argument based
>
> - cls(kwd1=arg1, kwd2=arg2...) keyword argument based
>
> - a mixture of the previous two options
>
> Adding some helpers along those lines to reprlib may make sense, but a
> meaningful ReprMixin places stronger constraints on the relationship
> between class attributes and the desired repr output than is
> appropriate for the standard library. It's way too idiosyncratic
> across developers to be worth promoting in the stdlib (a project or
> domain specific class hierarchy is a different story, but that's not
> relevant for a general purpose ReprMixin proposal).

instead of the ReprMixin, how about a descriptor

the Api would change to something like

class User(object):
   __repr__ = FormatRepr('<User {name!r}')

its less concise, but actually more straightforward and better decoupled 
(thanks for hinting at the strong coupling in the class hierarchy)

and ArgRepr and KwargRepr could be added in a similar fashion

Cheers,
Ronny
>
> Cheers,
> Nick.
>




More information about the Python-ideas mailing list