Code Explanation:
1. Function Definition
def add_entry(key, value, data={}):
Function Name: add_entry
Parameters:
key: The key to add to the dictionary.
value: The value to assign to the key.
data={}: A mutable default argument — this is important and causes unexpected behavior.
2. Function Logic
data[key] = value
return data
The function adds the key-value pair to the data dictionary.
Then it returns the updated dictionary.
3. Function Calls
print(add_entry('a', 1))
print(add_entry('b', 2))
This is where the mutable default argument issue shows up.
4. What Happens Internally
First Call:
add_entry('a', 1)
data is the default {}.
'a': 1 is added.
Returns: {'a': 1}
Second Call:
add_entry('b', 2)
You might expect a new dictionary, but Python reuses the same data dictionary from the previous call.
'b': 2 is added to the same dictionary.
Returns: {'a': 1, 'b': 2}
5. Output
{'a': 1}
{'a': 1, 'b': 2}


0 Comments:
Post a Comment