Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What does an empty dictionary mean in Python?

In Python, an empty dictionary means that it does not contain key-value pair elements. In this example to create an empty dictionary, we can use a dict constructor and this method takes no arguments. If no argument is passed then it creates an empty dictionary.

What is the value of an empty dictionary in Python?

Python empty dictionary means that it does not contain any key-value pair elements. To create an empty dictionary in this example, we can use a dict(), which takes no arguments. If no arguments are provided, an empty dictionary is created.

Is empty dictionary false Python?

If the dictionary is empty, it returns None which is not == False .

How do you pass an empty dictionary in Python?

To create an empty dictionary, first create a variable name which will be the name of the dictionary. Then, assign the variable to an empty set of curly braces, {} . Another way of creating an empty dictionary is to use the dict() function without passing any arguments.


Let's look at an example:

def f(value, key, hash={}):
    hash[value] = key
    return hash

print(f('a', 1))
print(f('b', 2))

Which you probably expect to output:

{'a': 1}
{'b': 2}

But actually outputs:

{'a': 1}
{'a': 1, 'b': 2}

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.