[Tutor] Good writeup on Python assignment semantics

Kent Johnson kent37 at tds.net
Tue Jul 17 17:58:12 CEST 2007


jim stockford wrote:
> 
> as I understand things...
> 
> there's a writeup somewhere that uses the term "bind" instead
> of "assign" for the operation
> a = b

Yes, that is how I prefer to talk about it - the effect of an assignment 
statement is to bind a name to a value.
> 
> for example, in Python
> a = 1
> the value 1 now has a name of a associated with it.
> 
> in C
> a = 1;
> creates an integer-sized area in RAM, names it a, and puts
> the value 1 in that area.

> I'm curious to know the practical value of knowing the
> difference: where can one get tripped up in this case?

The problems come with mutable values. For example,

a = []
b = a
b.append(1)

What is the current value of a? If your model of variables is storage 
containers, and your model of assignment is copying, you will expect 
that a and b are different lists and a==[]. But in Python, a and b are 
names for the same value, so a==b==[1].

This can occur in more subtle ways also. For example, parameter passing 
has the same semantics as assignment - it binds a name in the local 
scope to the passed-in value. If you pass a list as a value and modify 
the list, the caller will see the modification. This may or may not be 
what you want; if you model parameter passing as copying values you will 
be surprised by this behaviour. If you take this behaviour to mean that 
values are passed "by reference", then you may be surprised when an 
assignment to the parameter name in a function *doesn't* affect the 
value at the caller. In other words, given
def f(x, y):
   x = 3
   y.append(1)

a = 5
b = []
f(a, b)

What are the current values of a and b? Without a correct model of 
parameter passing you will not answer correctly.

Kent


More information about the Tutor mailing list