[Python-ideas] Computed attribute names (Re: Assignment decorators)
Greg Ewing
greg.ewing at canterbury.ac.nz
Fri Mar 4 06:23:42 CET 2011
Steven D'Aprano wrote:
> setattr(x, name, getattr(x, name, 0)+1)
>
> looks like one line to me.
No, that's not quite the same thing, because it doesn't
invoke the *in-place* + operation.
It's true that it could be written as
setattr(x, name, getattr(x, name, 0).__iadd__(1))
but that's getting really hard to read. The three lines
come from trying to write it in a way that doesn't obscure
what's being done:
y = getattr(x, name)
y += 1
setattr(x, name, y)
> the obvious helper function makes it easy to write that as (say)
>
> incattr(x, name, 1)
That takes care of +=. Now you just need another one for
each of the 20-odd other in-place operations. :-)
--
Greg
More information about the Python-ideas
mailing list