Issue with function keyword defaults

Emile van Sebille emile at fenx.com
Tue Aug 21 21:40:26 EDT 2001


Try it like this instead:


>>> import time
>>> def test(r=None):
...     if r == None: r = {}
...     r[time.time()] = time.time()
...     return r
...
>>> test()
{998444336.66199994: 998444336.66199994}
>>> test()
{998444338.24399996: 998444338.24399996}
>>> test()
{998444340.17700005: 998444340.17700005}
>>>

--

Emile van Sebille
emile at fenx.com

---------
"Steve Holden" <sholden at holdenweb.com> wrote in message
news:qYDg7.100090$rV6.4889978 at e420r-atl2.usenetserver.com...
> "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