pythong referencing/aliasing

Gerhard Häring gh at ghaering.de
Fri Apr 25 17:28:04 CEST 2003


Howe wrote:
> How does Python handles variable references/aliases?
> 
> Example:
> 
> a = 1

A new int object with the value 1 is created. The variable a references 
this int object.

> b = (REF)a

In Python: b = a

b now refers to the same object a does.

> b = 2

A new int object with the value 2 is created. b now references this int 
object instead of the one with the value 1.

Objects not referenced any more (like this one) will eventually be 
garbage-collected. [1]

> print a
> 
> In this case, since "b" is just a reference to "a", changes to "b"
> automatically change "a".
> 
> Does python have this ability?

Sure. This, however, only works with mutable objects. ints (and strings, 
and tuples) are immutable. An example for a mutable object would be a 
list (or a class instance). Try this, for example:

C:\src\python\dist\src>python
'import site' failed; use -v for traceback
Python 2.3a2+ (#27, Apr 23 2003, 21:13:49)
[GCC 3.2.2 (mingw special 20030208-1)] on mingw32_nt-5.11
Type "help", "copyright", "credits" or "license" for more information.
 >>> a = [3]	# create a list with one element, 3
 >>> b = [4]	# create a list with one element, 4
 >>> a, b	# display both
([3], [4])
 >>> b = a	# b references the object a refers to; nothing else 
references the [4] list, so it will be garbage collected, eventually
 >>> a,b		# display both
([3], [3])
 >>> a.append(4)	# append the item 4 to the list a (and b) refers to
 >>> a,b		# print both
([3, 4], [3, 4])
 >>> ^Z

-- Gerhard

[1] ints are a bad excample, because they're special-cased in the 
CPython implementation.





More information about the Python-list mailing list