Python> default argument does not initialize mutable object (eg list) / because it is initialized at definition

@ Introducing Python: Modern Computing in Simple Packages by Bill Lubanovic (No. 2550 / 12833)

Default argument values are calculated when the function is defined, not when it is run. A common error with new (and sometimes not-so-new) Python programmers is to use a mutable data type such as a list or dictionary as a default argument.

As an example http://ideone.com/66DaME

def buggy(arg, result=[]):
	result.append(arg)
	print(result)
 
buggy('a')
buggy('b')

result


['a']
['a', 'b']

It will be as follows.

http://ideone.com/9bsPfY

def nobuggy(arg, result=None):
	if result is None:
		result = []
	result.append(arg)
	print(result)
	
nobuggy('a')
nobuggy('b')

result


['a']
['b']

Reference ?: Interpretation of arguments and construction of values

The "default argument" could not be searched in the standard document.

Recommended Posts

Python> default argument does not initialize mutable object (eg list) / because it is initialized at definition
Python list is not a list
Python does not output errors or output just because the indent is misaligned
Do not specify a mutable object (list type, dictionary type, etc.) as the initial value of the function argument of python.