The � debate
Marko Rauhamaa
marko at pacujo.net
Sat May 10 04:18:59 EDT 2014
Chris Angelico <rosuav at gmail.com>:
> On Sat, May 10, 2014 at 3:58 PM, Gregory Ewing
> <greg.ewing at canterbury.ac.nz> wrote:
>> Steven D'Aprano wrote:
>>>
>>> some_function(x, y+1)[key].attribute[num](arg)[spam or eggs] = 42
>>>
>>> I'm pretty sure that it isn't common to call the LHS of that assignment a
>>> variable.
>
> [...]
> https://en.wikipedia.org/wiki/Assignment_(computer_science)
>
> [...]
>
> So if Python has no variables, then either that article is
> inappropriate, or Python has no assignment either.
Many complaints against Python's variables are really comments on
Python's object model.
Steven's example points out a different angle: many complaints against
Python's variables are really comments on Python's assignment statement
(including argument passing).
In Python,
x is a variable, a memory slot that can be assigned to,
a[3] is a list element, a memory slot that can be assigned to,
d['y'] is a dict entry, a memory slot that can be assigned to,
o.f is a field, a memory slot that can be assigned to
Now, Python (together with a host of other programming languages) lacks
a way to pass memory slots by reference (although the list/dict+key
comes close). However, the fact that you can't get a reference to a
variable/list element/dict entry/field doesn't mean Python doesn't have
variables/list elements/dict entries/fields.
Marko
PS I have mentioned before that Python 3 *does* allow you to pass a
reference to any LHS by constructing an ad-hoc accessor object:
x, y = 2, 3
class X:
def get(self): return x
def set(self, v): nonlocal x; x = v
class Y:
def get(self): return y
def set(self, v): nonlocal y; y = v
swap(X(), Y())
print(x, y)
=> 3, 2
Such ad-hoc accessor classes are required for nonglobal variables only.
Generic accessor classes can be written for global variables, list
elements, dict entries and fields.
More information about the Python-list
mailing list