As the title says, I will explain the reason.
I made the following function. At first glance, I feel that any problem is in the content.
def A_fnc (b=dict()):
b["xxx"]=12
return b
#I will use it like this
aa=A_fnc()
bb=A_fnc()
aa["yyy"]=11
print(aa)
print(bb)
For some reason ... The output is as follows.
{'xxx': 12, 'yyy': 11}
{'xxx': 12, 'yyy': 11}
Both have the same content.
Note: Why are default values shared between objects? https://docs.python.org/ja/3/faq/programming.html#id14
It's easy to expect that a function call will create a new object for the default value. Actually, that is not the case. The default value is generated only once when the function is defined. As in the dictionary in this example, when that object is modified, subsequent function calls refer to the modified object.
For the time being, I did the following.
def A_fnc(b=False):
if(not b):b=dict()
b["xxx"]=12
return b
aa=A_fnc()
bb=A_fnc()
aa["yyy"]=11
print(aa)
print(bb)
#{'xxx': 12, 'yyy': 11}
#{'xxx': 12}
For the time being, this is the solution
Mr. @shiracamus pointed out. Thank you very much.
Recommended Posts