[Tutor] Re: confusion with dictionaries
Lee Harr
missive at hotmail.com
Thu Dec 18 21:14:52 EST 2003
>I was playing around with dictionaries, and came across something which I
>found rather... unexpected. here's a demonstration:
>
>>>>def foo(l = {}):
>... l[random.choice(string.lowercase)] = random.random()
>... return l
>>>>foo()
>{'m': 0.33204172040918167}
>>>>foo()
>{'m': 0.33204172040918167, 'l': 0.49843519723518959}
>I thought that if the dictionary 'l' was not stored in a variable outside
>the
>function it would be erased whenever the function foo() was terminated.
>
That is pretty much true. The trick is that the default values for
parameters are evaluated only once -- when the function is created.
And since the function itself still exists, the dictionary it uses for that
default value has to be kept alive too.
If you want a new dict with each call, try something like this:
def foo(l=None):
if l is None:
l = {}
I believe that is the standard python idiom. It's the one I use
regularly, anyhow.
_________________________________________________________________
Add photos to your e-mail with MSN 8. Get 2 months FREE*.
http://join.msn.com/?page=features/featuredemail
More information about the Tutor
mailing list