Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

empty dictionary as default value for keyword argument in python function: dictionary seems to not be initialised to {} on subsequent calls? [duplicate]

Here's a function. My intent is to use keyword argument defaults to make the dictionary an empty dictionary if it is not supplied.

>>> def f( i, d={}, x=3 ) : ...     d[i] = i*i ...     x += i ...     return x, d ...  >>> f( 2 ) (5, {2: 4}) 

But when I next call f, I get:

>>> f(3) (6, {2: 4, 3: 9}) 

It looks like the keyword argument d at the second call does not point to an empty dictionary, but rather to the dictionary as it was left at the end of the preceding call. The number x is reset to three on each call.

Now I can work around this, but I would like your help understanding this. I believed that keyword arguments are in the local scope of the function, and would be deleted once the function returned. (Excuse and correct my terminology if I am being imprecise.)

So the local value pointed to by the name d should be deleted, and on the next call, if I don't supply the keyword argument d, then d should be set to the default {}. But as you can see, d is being set to the dictionary that d pointed to in the preceding call.

What is going on?

Is the literal {} in the def line in the enclosing scope?

This behavior is seen in 2.5, 2.6 and 3.1.

like image 958
Andrej Panjkov Avatar asked Apr 19 '11 07:04

Andrej Panjkov


People also ask

How do you pass an empty dictionary in Python?

In Python to create an empty dictionary, we can assign no elements in curly brackets {}. We can also create an empty dictionary by using the dict() method it is a built-in function in Python and takes no arguments.

Why is the empty dictionary a dangerous default value in Python?

It's dangerous only if your function will modify the argument. If you modify a default argument, it will persist until the next call, so your "empty" dict will start to contain values on calls other than the first one. Yes, using None is both safe and conventional in such cases.

What is the default value of dictionary in Python?

default defaults to None . Return the value for key if key is in the dictionary, else default . If default is not given, it defaults to None , so that this method never raises a KeyError . In the above code, you use .

Why shouldn't you make the default arguments an empty list?

Answer: d) is a bad idea because the default [] will accumulate data and the default [] will change with subsequent calls.


1 Answers

>>> def f(i, d=None, x=3): ...     if not d: ...         d={} ...     d[i] = i*i ...     x += i ...     return x,d ...  >>> f(2) (5, {2: 4}) >>> f(3) (6, {3: 9}) >>>  
like image 143
dting Avatar answered Oct 13 '22 18:10

dting