
Why not simply do this : class MyClass: def _set_multiple(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) def __init__(self, a, b, c): self._set_multiple(a=a, b=b, c=c) -> No new syntax, no inspection, simple to read, parse and understand, and explicit. And you could directly do some simple cleanings or not define a variable, like : class MyClass: def _set_multiple(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) def __init__(self, a, b, c): self._set_multiple(a=a * 2, b=clean_field(b)) - Brice Le 25/04/17 à 03:08, Erik a écrit :
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. _______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/