[Python-ideas] Assignment decorators (Re: The Descriptor Protocol...)
Joao S. O. Bueno
jsbueno at python.org.br
Fri Mar 4 01:06:31 CET 2011
Hi Guido -
On Thu, Mar 3, 2011 at 8:15 PM, Guido van Rossum <guido at python.org> wrote:
> Greg, what is your use case for passing the lhs name into the
> function? Because that seems to be your purpose.
>
> Also it seems that one couldn't decorate all but the simplest assignments:
>
> @dec
> lhs = rhs
> # lhs = dec('lhs', rhs)
Really I don't perceive these as issues - in one hand, it might be
desired that just simple assignments would work, and kinds that would
result in complicated implementations or hard to read code,
could always raise syntax error, but I could imagine:
> @dec
> lhs.attr = rhs
> # lhs.attr = dec('lhs.attr', rhs) ???
setattr (lhs, 'attr', dec('attr', rhs) )
> @dec
> lhs[i] = rhs
> # lhs[i] = dec('??????', rhs)
Maybe this could simply raise a syntax error,
but
lhs.__setitem__(i, dec(str(i), rhs)) is not unthinkable
>
> @dec
> lhs1, lhs2, lhs3 = rhs
> # lhs1, lhs2, lhs3 = dec('???????????', rhs)
lhs1,lhs2, lhs3 = (('lhs1', 'lhs2', 'lhs3'), rhs)
> The use case I can think of for the first example would be to declare
> fields in a model class that know their own field name, as in Django
> and AppEngine models, and many other libraries. But that use case is
> covered pretty well by metaclasses,
The problem I see with the way this is currently done is that it is invisible -
as in "not explicit". The metaclass sets an object attribute in way that can
only be viewed on the documentation of the metaclass (which is usually
misinformed as
documentation on the superclass for these libraries).
Moreover, the mechanism to do this through metaclasses is a bit complex, so that
even reasonably proficient programmers perceive this kind of behavior
as magic that "just works".
> and the @decorator syntax has the
> disadvantage of requiring at least two lines per field, whereas the
> current solution requires only one line (and there is no explicit
> repetition of the field name -- the metaclass takes care of it).
As for the syntax, we can figure out one to work best - be it
decorators, the "def.... as ... " approach, or something else, - but I
think there are use cases for that. As I pointed out in the other
message,
the "constants" that have being discussed recently on python-dev could
also benefit from a feature like this.
regards,
js
-><-
>
> --Guido
>
More information about the Python-ideas
mailing list