[Python-ideas] Augmented assignment syntax for objects.
Erik
python at lucidity.plus.com
Mon Apr 24 21:08:05 EDT 2017
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. Apologies if I'm rehashing an old argument ;)
I often find myself writing __init__ methods of the form:
def __init__(self, foo, bar, baz, spam, ham):
self.foo = foo
self.bar = bar
self.baz = baz
self.spam = spam
self.ham = ham
This seems a little wordy and uses a lot of vertical space on the
screen. Occasionally, I have considered something like:
def __init__(self, foo, bar, baz, spam, ham):
self.foo, self.bar, self.baz, self.spam, self.ham = \
foo, bar, baz, spam, ham
... just to make it a bit more compact - though in practice, I'd
probably not do that with a list quite that long ... two or three items
at most:
def __init__(self, foo, bar, baz):
self.foo, self.bar, self.baz = foo, bar, baz
When I do that I'm torn because I know it has a runtime impact to create
and unpack the implicit tuples and I'm also introducing a style
asymmetry in my code just because of the number of parameters a method
happens to have.
So why not have an augmented assignment operator for object attributes?
It addresses one of the same broad issues that the other augmented
assignment operators were introduced for (that of repeatedly spelling
names).
The suggestion therefore is:
def __init__(self, foo, bar, baz, spam, ham):
self .= foo, bar, baz, spam, ham
This is purely syntactic sugar for the original example:
def __init__(self, foo, bar, baz, spam, ham):
self.foo = foo
self.bar = bar
self.baz = baz
self.spam = spam
self.ham = ham
... so if any of the attributes have setters, then they are called as
usual. It's purely a syntactic shorthand. Any token which is not
suitable on the RHS of the dot in a standard "obj.attr =" assignment is
a syntax error (no "self .= 1").
The comma-separators in the example are not creating a tuple object,
they would work at the same level in the parser as the import
statement's comma-separated lists - in the same way that "from pkg
import a, b, c" is the same as saying:
import pkg
a = pkg.a
b = pkg.b
c = pkg.c
... "self .= a, b, c" is the same as writing:
self.a = a
self.b = b
self.c = c
E.
More information about the Python-ideas
mailing list