[Python-ideas] FormatRepr in reprlib for declaring simple repr functions easily
Mike Graham
mikegraham at gmail.com
Thu May 31 16:38:37 CEST 2012
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 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
More information about the Python-ideas
mailing list