[Python-ideas] FormatRepr in reprlib for declaring simple repr functions easily

Alexandre Zani alexandre.zani at gmail.com
Thu May 31 16:51:45 CEST 2012


I would prefer an interface where I just pass a list of attribute
names and the utility class figures everything else out.

That said, I'm not sure this does enough to warrant inclusion in the
stdlib. It's easy enough to write a __repr__ with just a few more
characters. I'm not sure that:

__repr__ = FormatRepr("<User {username}>"

is actually more readable than

def __repr__(self):
  return "<User %s>" % self.username

In fact, the second option might be better because I don't have to
learn anything new to understand it. If I see your version, I have to
google it and then use brain-space to hold that feature in memory. If
I know python, I already know what the second option means.

Alexandre Zani

On Thu, May 31, 2012 at 7:43 AM, Ronny Pfannschmidt
<Ronny.Pfannschmidt at gmx.de> wrote:
> On 05/31/2012 04:38 PM, Mike Graham wrote:
>>
>> On Wed, May 30, 2012 at 11:03 AM, Ronny Pfannschmidt
>> <Ronny.Pfannschmidt at gmx.de>  wrote:
>>>
>>> Hi,
>>>
>>> i consider my utility class FormatRepr finished,
>>> its currently availiable in
>>> ( http://pypi.python.org/pypi/reprtools/0.1 )
>>>
>>> it supplies a descriptor that allows to simply declare __repr__ methods
>>> based on object attributes.
>>>
>>> i think it greatly enhances readability for those things,
>>> as its DRY and focuses on the parts *i* consider important
>>> (e.E. what accessible attribute gets formatted how)
>>>
>>> there is no need ot repeat attribute names or
>>> care if something is a property,class-attribute or object attribute
>>> (one of the reasons why a simple .format(**vars(self)) will not always
>>> work)
>>>
>>> oversimplified example:
>>>
>>>
>>> .. code-block:: python
>>>
>>>   from reprtools import FormatRepr
>>>
>>>   class User(object):
>>>       __repr__ = FormatRepr("<User {name}>")
>>>
>>>       def __init__(self, name):
>>>           self.name = name
>>>
>>>
>>>
>>>>>> User('test')
>>>
>>> <User test>
>>
>>
>> If we introduce something like this, I think I'd prefer an approach
>> that didn't encourage hardcoding "User". In my __repr__s, I usually
>> make the class's name dynamic so it does not make for confusing reprs
>> in the event of subclassing.
>
>
> you can just use {__class__.__name__} to have it "softcoded"
>
>
>>
>> You really don't end up implementing __repr__ all that often and if
>> you do you writing a simple one isn't hard. I'm -0 on having this in
>> the stdlib.
>>
>> Mike
>
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas



More information about the Python-ideas mailing list