Clarification on python intro
Alan Garrison
aeg@lbwl.com
Tue, 09 May 2000 09:38:33 -0400
For those at the meeting (or are currently learning python), there was
a little confusion on my part about calling functions with mutable
objects. I wrote some test code to clarify what Tim brought up:
>>> # create three local lists (mutable objects)
>>> loc1 = [1,2,3]>>> loc2 = ["a","b","c"]>>> loc3 = ["d","e","f"]>>> # create function to test mutability>>> def Dinsdale(arg1,arg2,arg3):... arg1[0] = "99" # first, change indexed value... arg1 = ["spam", "SPAM", "SPAM!!!"] # second, create new list instance... arg2 = [44,45,46] # first, create new list instance... arg2[0] = 55 # second, change indexed value... arg3 = "Assigning the argument to be a new type"... >>> Dinsdale(loc1,loc2,loc3) # call function with our locals>>> print loc1 # should have [0] index changed['99', 2, 3]>>> print loc2 # should not change['a', 'b', 'c']>>> print loc3 # should not change['d', 'e', 'f']>>>
As you can see, function Dinsdale was passed three lists (mutable),
but only loc1 was changed at all. Note the order of the arg#
changes in the funciton. If I change an indexed part of the list
first, it is changed outside the function. If I give it a whole
new list (arg1 = ["spam", "SPAM", "SPAM!!!"]), or any other new
object type (arg3 = "Assigning the argument to be a new type"),
a new object is created in the function and the reference to the
loc# object is lost (within the function at least). This is
basically what Ben explained, so the above code should hopefully
clarify things.