pythong referencing/aliasing

Gerhard Häring gh at ghaering.de
Fri Apr 25 13:24:11 EDT 2003


Joshua Marshall wrote:
> Kevin Howe <khowe at perfnet.ca> wrote:
> 
>>How does Python handles variable references/aliases?
> 
> 
>>Example:
> 
> 
>>a = 1
>>b = (REF)a
>>b = 2
>>print a
> 
> 
>>In this case, since "b" is just a reference to "a", changes to "b"
>>automatically change "a".
> 
> 
>>Does python have this ability?
> 
> You're basically asking two questions, and both answers are "no".
> There is no way to associate two variables the same address, and there
> is no REF/address-of operator in Python.

Such an operator isn't necessary because creation of references is the 
default behaviour in Python.

Note that the assignment operator never changes an existing object. All 
it does is bind a name to an object. This object might already exist, 
like in:

#v+
a = 5	# Create the int object with the value 5 and bind the name 'a' to it
b = a	# bind the name 'b' to the object 'a' refers to
#v-

As  you seem to have a C background (wild guess), here's the C version:

#v+
PyObject* a;
PyObject* b;

a = PyInt_FromLong(5L);
b = a;	/* reference semantic, i. e. *not* *b = *a */
#v-

For the full glory, read the language specification: 
http://python.org/doc/current/ref/objects.html
It makes it very clear how things work.

Alternatively, you might create a new object in the second call, like in:

#v+
a = 5	# Create the int object with the value 5 and bind the name 'a' to it
a = 6	
# <-- Create the int object with the value 6 and bind the name 'a' to
# it. The previously created object int(5) isn't referenced any longer,
# so it is garbage-collected.
#v-

Here's the C function for you pointer-aficionados:

PyObject* a;

#v+
a = PyInt_FromLong(5L); /* reference count of 'a' is now 1 */

/* derease reference count of a. it is 0 now. Python can then 
garbage-collect it eventually. */
Py_DECREF(a);

a = PyInt_FromLong(6L);
#v-

> As others have mentioned, you might be able to use lists to give you
> the behavior you're looking for.

For assignments, Python doesn't treat immutable (such as ints) and 
mutable (such as lists) objects differently. The reference semantics are 
the same, no matter which type of object is involved.

-- Gerhard





More information about the Python-list mailing list