[Edu-sig] How does Python do Pointers?
macquigg at ece.arizona.edu
Tue May 6 00:06:13 CEST 2008
Many thanks to Michael, Anna and John for the very thorough answers to this question. I especially like John's sticky-note analogy. I have been using a similar analogy with "labels", but that gets confused with the other more common uses of the word "label". Sticky Note is unique and more memorable.
I'm disturbed that there doesn't seem to be any agreement on simple definitions for "call by reference" and "call by value". A Google search for [python "call by value"] shows there is widespread confusion in the Python world. I'm not a computer scientist, but somewhere I did learn these concepts as being simply copying the value of a variable vs passing just a reference to the original. I see that my simple understanding agrees with Kernighan and Ritchie and with http://en.wikipedia.org/wiki/Call_by_value. (Note that "call-by-reference", as defined in this article, clearly includes Python's calling method.)
Luckily, we can answer the question without wading into this swamp. Here is my latest revision:
Python doesn't need pointers because of the simple relationship between variables and the objects they refer to. A variable has a name and a pointer to an object. An object has a type, a value, and an address in memory. Unlike C, the type is with the object, not the variable. A variable is "bound" to an object much like a sticky note on a box. Notes can be moved from one box to another, and a box can have more than one note, or no notes at all.
Python's pointers are "under the hood", not something the programmer sees or ever needs to worry about. This part of what makes Python a higher level language than C. You gain a lot in simplicity and readability, while losing the ability to work directly with memory addresses. You also lose a little memory, because objects are more complex than raw data values.
The sticky-note analogy has a flaw. You can't stick one note on top of another. When you say x = y = z, all three variables now point to the object originally pointed to by z. Then when you say y = 8, y now points to an integer object 8, but x doesn't move with y. Python's "sticky notes" have a special glue that sticks only to an object, not to another variable.
See http://effbot.org/zone/python-objects.htm for more on Python objects and variables.
Note: You can get the address of an object x with the function id(x), but this is used only to provide a unique identity for the object, not to access it. If id(x) == id(y), you know that variables x and y both point to the same object.
More information about the Edu-sig