[Tutor] confusion with dictionaries
Karl Pflästerer
sigurd at 12move.de
Fri Dec 19 12:31:21 EST 2003
On 19 Dec 2003, Thomi Richards <- thomi at imail.net.nz wrote:
> 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
[...]
> 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.
No. Some days ago we had a thread here with exactly the same problem.
Don't you read the list?
I cite from the Python tutorial:
,----[ Python tutorial ]
| *Important warning:* The default value is evaluated only once. This
| makes a difference when the default is a mutable object such as a list,
| dictionary, or instances of most classes. For example, the following
| function accumulates the arguments passed to it on subsequent calls:
|
| def f(a, L=[]):
| L.append(a)
| return L
|
| print f(1)
| print f(2)
| print f(3)
|
| This will print
|
| [1]
| [1, 2]
| [1, 2, 3]
|
| If you don't want the default to be shared between subsequent calls,
| you can write the function like this instead:
|
| def f(a, L=None):
| if L is None:
| L = []
| L.append(a)
| return L
`----
So what happens here is that your default value gets only once
evaluated: the time you create the function. All further calls to the
function which don't give the default value will use exactly the same
dictionary: the one which was created the moment the function definition
was evaluated.
> This is very wierd... can anyone explain this? Furthermore, how can I ensure
see above.
> that a dictionary is clean when passing it as an optional argument to a
> function like this?
When you pass a dictionary the default one won't get used. So there's
no problem. Or use the technique shown in the tutorial.
Karl
--
Please do *not* send copies of replies to me.
I read the list
More information about the Tutor
mailing list