default argument value is mutable

jmp jeanmichel at sequans.com
Fri Oct 7 07:55:30 EDT 2016


On 10/07/2016 01:38 PM, Daiyue Weng wrote:
> Hi, I declare two parameters for a function with default values [],
>
> def one_function(arg, arg1=[], arg2=[]):
>
> PyCharm warns me:
>
> Default argument value is mutable,
>
> what does it mean? and how to fix it?
>
> cheers
>

You'll run into this bug

def foo(a=[]):
	a.append('item')
	print a

foo()
foo()

['item']
['item', 'item'] #what ?? 2 'item' ??

default argument are evaluated when defining the function, meaning the 
list you bound to the default argument is shared by all the function calls.

Easily fixed:

def foo(a=None):
   a = [] if a is None else a
   print a

foo()
foo()

['item']
['item']

So the rule of thumb for default argument value is "No mutable"

Cheers,

Jm

note : python 2.7 code




More information about the Python-list mailing list