function scope
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Mon Feb 2 23:25:53 EST 2009
On Mon, 02 Feb 2009 16:37:07 -0800, Mike Kent wrote:
> On Feb 2, 6:40 pm, Baris Demir <demirba... at gmail.com> wrote:
>
>> def simpleCut(d=dict()):
>> temp=d
>> for i in temp.keys():
>> if (temp[i] == .......) :
>> temp[i]=new_value
>> return temp
>
> You have been bitten by the shared default parameter noobie trap:
No, he has tripped over the assignment-doesn't-make-copies feature.
Ignore the default value, and consider passing in a dict:
def simpleCut(d=dict()):
temp=d
# ...
That doesn't make a temporary copy of d, it makes a new name that refers
to the same dictionary as d. So if you do this:
li = {'x': 1}
f = simpleCut(li)
then
assert f is li
will pass, and he will be surprised and dismayed to discover that
simpleCut() has side-effects.
Solution: make a copy of the input.
def simpleCut(d=dict()):
temp = d.copy()
for i in temp: # don't need to call keys()
if (temp[i] == ...):
temp[i] = new_value
return temp
--
Steven
More information about the Python-list
mailing list