Do not specify a mutable object (list type, dictionary type, etc.) as the initial value of the function argument of python.

background

As the title says, I will explain the reason.

Contents

phenomenon

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.

Cause

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.

Solution

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

reference

Mr. @shiracamus pointed out. Thank you very much.

Recommended Posts

Do not specify a mutable object (list type, dictionary type, etc.) as the initial value of the function argument of python.
Get the value of a specific key in a list from the dictionary type in the list with Python
How to write a list / dictionary type of Python3
[python] Value of function object (?)
[Python] Use JSON format data as a dictionary type object
Extract the value of dict or list as a string
Precautions when using a list or dictionary as the default argument
If you give a list with the default argument of the function ...
[Python] What is a formal argument? How to set the initial value
[Python3] Rewrite the code object of the function
[python] [meta] Is the type of python a type?
[Python] I tried to get the type name as a string from the type function
Get the caller of a function in Python
Make a copy of the list in Python
Note: The meaning of specifying only * (asterisk) as an argument in the Python function definition.
Notification of weather forecast (rain, etc.) by DM as a part of the function of bot
Don't take an instance of a Python exception class directly as an argument to the exception class!
[Python of Hikari-] Chapter 06-02 Function (argument and return value 1)
Specify a subcommand as a command line argument in Python
[Python] Calculate the average value of the pixel value RGB of the object
Summary of Python sort (list, dictionary type, Series, DataFrame)
Python: Get a list of methods for an object
Check the argument type annotation when executing a function in Python and make an error
Different from the import type of python. from A import B meaning
Get the number of specific elements in a python list
[Python] Type Error:'in <string>' requires string as left operand, not list
[Python3] Call by dynamically specifying the keyword argument of the function
How to get the last (last) value in a list in Python
Python: Create a dictionary from a list of keys and values
The websocket of toio (nodejs) and python / websocket do not connect.
2015-11-26 python> Display the function list of the module> import math> dir (math)
Extract the value closest to a value from a Python list element
Python> default argument does not initialize mutable object (eg list) / because it is initialized at definition
Addictive note: max (max (list)) must not be used when maxing the value of a 2D array
Python list is not a list
When incrementing the value of a key that does not exist
Save the result of the life game as a gif with python
Find the optimal value of a function with a genetic algorithm (Part 2)
Format when passing a long string as an argument of python
[Python] Execution time when a function is entered in a dictionary value
How to check the memory size of a dictionary in Python
[Python3] Define a decorator to measure the execution time of a function
Utilization of lambda (when passing a function as an argument of another function)
python note: map -do the same for each element of the list
Finding the optimum value of a function using a genetic algorithm (Part 1)
What to do when the value type is ambiguous in Python?
[Python] A simple function to find the center coordinates of a circle
[Python] A program that rotates the contents of the list to the left