Issue with function keyword defaults

Roman Suzi rnd at onego.ru
Sun Aug 5 10:06:55 EDT 2001


On Sun, 5 Aug 2001, Morten W. Petersen wrote:

>Hi,
>
>after trying to set an empty dictionary as a default keyword arguments'
>value, this happened (same thing happened on 2.0.1 BTW):
>
>morten at debian:~$ python
>Python 1.5.2 (#0, Apr 10 2001, 10:03:44)  [GCC 2.95.3 20010219
>(prerelease)] on linux2 Copyright 1991-1995 Stichting Mathematisch
>Centrum, Amsterdam
>>>> import time
>>>> def test(r={}):
>...     r[time.time()] = time.time()
>...     return r
>...
>>>> test()
>{997015577.922: 997015577.922}
>>>> test()
>{997015578.849: 997015578.849, 997015577.922: 997015577.922}
>>>> test()
>{997015579.446: 997015579.446, 997015578.849: 997015578.849,
> 997015577.922: 997015577.922
>
>I would assume that r would be re-initialized on every call, but that's
>not happening;  could anyone explain this behaviour?

This is widely known trap. r is ONE instance for all function
calls. Better (idiomatic) approach is:

def test(r=None):
    r = r or {}
    r[time.time()] = time.time()
    return r

(Same happens for all mutable objects. The rule is not to
put mutables as default values unless the effect is wanted or
they aren't modified.)


Sincerely yours, Roman Suzi
-- 
_/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/
_/ Sunday, August 05, 2001 _/ Powered by Linux RedHat 6.2 _/
_/ "By all means, let's not confuse ourselves with the facts!" _/





More information about the Python-list mailing list