Default values for function args
RootBoy
xyz at spud.dink.net
Tue Jan 11 19:31:13 EST 2000
On Tue, 11 Jan 2000 04:05:49 GMT, Joshua Macy <amused at webamused.com> wrote:
>>
>> Maybe you're thinking that assignment will create a copy of an object,
>> instead of a copy of a reference to an object? In Python assignment
>> always stores references to objects, not copies of the objects
>> themselves. In a statement like
>>
>> target = expression
>>
>> expression yields an object, and the assignment stores a reference to
>> the object in target. If the expression is simply the name of a
>> variable, after the assignment both variables have references to the
>> same object. This is what's happening in the list example you created.
>> To create a copy of an object, you have to take an extra step, as in
>> the example I gave where I used the slice operation ([:]) to create a
>> copy of the sequence that contained everything the original sequence
>> did, and then assigned the reference to that new object to my variable.
>> For instance, if explicitly created a copy of local_list before
>> returning the reference, your function would have behaved as you
>> expected:
>>
>>
>> >>> def fn(a, local_list=[]): # local_list object gets created here
>> ... local_list.append(a)
>> ... return local_list[:] # a copy of local_list is created and
>> returned
>> ...
>> >>> list1 = fn('xyzzy')
>> >>> print list1
>> ['xyzzy']
>> >>> list2 = fn(3.14)
>> >>> print list1, list2
>> ['xyzzy'] ['xyzzy', 3.14]
>> >>> list3 = fn(1000)
>> >>> print list1, list2, list3
>> ['xyzzy'] ['xyzzy', 3.14] ['xyzzy', 3.14, 1000]
>> >>>
>>
>> Does that help at all?
Yes, it's finally clear. I had overlooked an important footnote in the
tutorial:
"Actually, call by object reference would be a better description, since
if a mutable object is passed, the caller will see any changes the callee
makes to it (e.g., items inserted into a list). "
Although this refers to passing arguments into a function, it also apparently
applies to return values. I had thought I was returning an entire list object
by passing the entire list by value on the stack. What actually happens is
that a reference to the object is what gets passed back to the caller by value
on the stack.
Thanks again....
More information about the Python-list
mailing list