Code Explanation:
Function Definition
def test(val, data={}):
The function test takes two parameters:
val: a required value.
data: an optional parameter with a default value of an empty dictionary {}.
Mutable Default Argument Trap
The default value {} is a mutable object (dictionary).
In Python, default arguments are evaluated only once, when the function is defined, not every time it’s called.
So if the function modifies that dictionary, the changes persist across function calls!
First Call: print(test(1))
data[1] = 1
Since no data is passed, it uses the default {}.
It adds the key-value pair 1: 1.
So now, data becomes {1: 1}.
The function returns this dictionary.
Output:
{1: 1}
Second Call: print(test(2))
Again, data is not passed, so it reuses the same dictionary from before, which is now {1: 1}.
data[2] = 2
This updates the same dictionary to {1: 1, 2: 2}.
It is returned.
Output:
{1: 1, 2: 2}
Final Output
{1: 1}
{1: 1, 2: 2}
.png)

0 Comments:
Post a Comment