Re: The “does Python have variables?” debate

Chris Angelico rosuav at gmail.com
Thu May 8 08:54:24 EDT 2014


On Thu, May 8, 2014 at 10:41 PM, Roy Smith <roy at panix.com> wrote:
> At some point, that model no longer fits reality well enough that it
> becomes a barrier to further learning.  When I write:
>
> def mutate(x, y):
>     x = 42
>     y[0] = 42
>
> x = 4
> y = [4]
>
> mutate(x, y)
> print x, y
>
> and run it, unless I really understand about name binding and argument
> passing, I'm going to be totally befuddled by the result.

Easiest way to explain that is probably to just say, right at the
beginning, that *assignment to a name is special*. When you assign to
x inside mutate(), stuff happens. You're not assigning to y, so
different stuff happens. If you called a method on y, or anything like
that, it'd be the same kind of "stuff" as you're seeing here; but
assigning directly to the name is a different sort of operation from
everything else. (Explaining the difference between "x = x + 1" and "x
+= 1" can come later. MUCH later, probably when you try to augassign
to a tuple's element.)

The advantage of singling out assignment is that, as well as handling
the difference between rebinding and mutation, it also picks up the
magic "this is now local" mode change. Compare:

x = [1,2,3]
def mutate1():
    x += [4]
def mutate2():
    x.append(4)

One of them needs a 'global' declaration to work, and the other
doesn't, because assigning is special.

ChrisA



More information about the Python-list mailing list