Is there a reference/alias/pointer in Python?

Daniel Eloff danieleloff at hotmail.com
Fri Jul 23 00:01:25 EDT 2004


"Basically every Python object is a pointer, a PyObject* in the C 
implementation.  So if you assign a variable to 
Users['current_users_username'] you have two references to the same 
object.  However, you can't use this fact to change the value of one 
variable through the other because you can't dereference and change the 
value of either.  All you can do is make the variable point to a new
object."

Ok I think I understand this part (after reading it through a couple of
times)

Your original variable is a PyObject* and Users creates another
PyObject* to the same PyObject. If you try to modify either PyObject
through the pointer, another PyObject is created and this is the one you
modify. (standard ref-counting implementation).

"All this is assuming that the variables are strings, which are
immutable 
  in Python, meaning that they cannot be changed in place.  If you have 
two indentifiers pointing to the same mutable object, such as a list, 
then you can change the value of one through the other by changing it in

place (e.g. assigning to an element of the list) rather than by 
re-assigning the variable."

If I understand this correctly, mutable objects like lists and
dictionaries function in much the same way (if you assigned it to
Users['current_users_username']) but when you attempt to modify the
object through either pointer you end up modifying the underlying object
and thus the changes will be reflected in both?

Am I close?



More information about the Python-list mailing list