How to Teach Python "Variables"

davisn90210 at gmail.com davisn90210 at gmail.com
Mon Nov 26 14:21:09 EST 2007


Hrvoje Niksic wrote:
> greg <greg at cosc.canterbury.ac.nz> writes:
>
> > none wrote:
> >>     IIRC, I once saw an explanation how Python doesn't have
> >> "variables" in the sense that, say, C does, and instead has bindings
> >> from names to objects.
> >

IMHO, this is nonsense.  All that variables are (in any language) are
"bindings" for names.  Pretending python does anything novel with
regard to "variables" is confusing and, ultimately, simply results in
a redefinition of terms programmers are already familiar with.  I
mean, it's kind of like saying my computer is not a computer but is
actually a device that follows input directions.  Of course that
description may be true (and I may even use it to explain to students
*what* a computer is), but it is no less a computer for it.

> > If you're talking to C programmers, just tell them that Python
> > variables always contain pointers. That should give them the right
> > mental model to build on.
>
> That is a convenient shortcut when it works, but in my experience it
> tends to confuse the issue.  The reason is that one of the main uses
> of pointers in C is implementing pass-by-reference.  A C programmer
> told that Python variables internally hold pointers expects this code:
>

I think most C programmers are smart enough to figure out the supposed
differences, with only a little additional explanation on the part of
the instructor.  Python's "variable model" is practically identical to
that of Java, after all, and I don't recall any discussion of
cataclysmic proportions over the differences between C "pointers" and
Java "references".  There are "differences" (or more accurately
"points of emphasis"), but of the sort that take a paragraph or two of
explanation/clarification -- not a completely new model.

> def func(a):
>   a = 10
> ...
> func(x)
>
> to change the value of x.

Depends on how you implement the C "equivalent".  The most direct
translation, IMHO, is the following:

  void func(int *a){
    a = 10; //Of course this is nonsense, but it illustrates the
point.  Just because "a" is a pointer
                 //does not mean that "a" is not rebound when it is
assigned to.  Oh wait!  Did I use
                 //the word "rebound" when talking about a *C*
variable? ;-)
    //*a = 10; //I'm guessing this is what *you* had in mind, but it
is very different
  }

  int main(int argc, char **argv){
    int x = 5;
    func(&x);
    printf("x is: %i\n", x);
    return 0;
  }

Which prints:
  x is: 5

In this case, both the C and Python code have the same result.

--Nathan Davis



More information about the Python-list mailing list