[Python-ideas] Reference variable in assignment: x = foo(?)

Chris Angelico rosuav at gmail.com
Fri Jul 12 05:02:38 CEST 2013


On Fri, Jul 12, 2013 at 12:51 PM, Corey Sarsfield <subbarker at gmail.com> wrote:
> Actually, what I wanted was to be able to reference the variable being
> assigned to

I think I understand what you're trying to say, but it's not something
that really exists in Python.

With a classic assignment statement:

foo = (expression)

the previous value of foo is abandoned and a new value bound to that
name. What you want is to reference that previous value (presumably
with the same potential for NameError or UnboundLocalError if there is
none). Effectively, elevate the magic of "foo = 5; foo += 10" to full
feature.

There HAVE been times when I've wanted something like this, but
they're extremely rare. Also, the nature of Python makes the benefit
somewhat less than it might be in, say, C++; it's not going to be
possible to do the lookups once and keep track of the memory location,
because Python simply doesn't work that way. Whether __setitem__ can
take advantage of a previous __getitem__ is entirely up to the class.

ChrisA


More information about the Python-ideas mailing list