Issue with function keyword defaults

Steve Holden sholden at holdenweb.com
Tue Aug 21 21:36:05 EDT 2001


"Morten W. Petersen" <morten at thingamy.net> wrote in message
news:Pine.LNX.4.21.0108051307240.31133-100000 at bcryachts.atsat.com...
> 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?
>

Yes. The default value is bound to the argument name at the time the def
statement is processed. Because it is a mutable value, you can (and do)
change the dictionary's contents, but the argument name is still bound to
the changed dictionary and so you see successive additions when you call
test() with no arguments.

regards
 Steve
--
http://www.holdenweb.com/









More information about the Python-list mailing list