[Python-ideas] Augmented assignment syntax for objects.

Nick Coghlan ncoghlan at gmail.com
Thu Apr 27 11:24:58 EDT 2017

On 25 April 2017 at 11:08, Erik <python at lucidity.plus.com> wrote:
> Hi. I suspect that this may have been discussed to death at some point in
> the past, but I've done some searching and I didn't come up with much.

Hi Erik,

Offering more concise ways of writing more powerful class definitions
is certainly a common topic of exploration in Python development.

A couple of folks have already mentioned Hynek Schlawack's `attrs`
packages, which pairs up a class decorator with particular kinds of
values set as class level attributes:

    from attr import attrs, attrib

    class MyClass:
        foo = attrib()
        bar = attrib()
        baz = attrib()

Here, the `attrs` decorator not only writes __init__ for you, but also
__repr__, comparison operators, pickle support, and a range of other
things. Glyph Lefkowitz put together a good post last year describing
just how much functionality attrs implicitly adds to a typical class
definition, all while making it shorter and less repetitive:

So I think if Python were to make any changes to the default toolset
in this area, it would be more along the lines of how `attrs` works
(i.e. offering a more declarative approach to the high level task of
defining structured data containers), than it would be along the lines
of a low level syntactic solution that only benefited `__init__` and
`__new__` without addressing any of the other repetitive aspects of
writing comprehensive class definitions.

For example, if we decided we wanted to go down that path, we could
add a new `autoclass` module and write the equivalent of the above as:

    from autoclass import make, field

    class MyClass:
        foo = field()
        bar = field()
        baz = field()

That would provide us with a clear terminological distinction between
autoclass fields and class attributes in general, while still letting
people eliminate a lot of the boilerplate currently involved in
writing classes that produce nice and easy to use instances.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list