default argument value is mutable

Steve D'Aprano steve+python at pearwood.info
Fri Oct 7 09:16:35 EDT 2016


On Fri, 7 Oct 2016 10: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?


The usual way to avoid that is:


def one_function(arg, arg1=None, arg2=None):
    if arg1 is None:
        arg1 = []  # gets a new list each call
    if arg2 is None:
        arg2 = []  # gets a new list each call



Otherwise, arg1 and arg2 will get the same list each time, not a fresh empty
list. Here is a simple example:

def example(arg=[]):
    print(id(arg), arg)
    arg.append(1)


py> def example(arg=[]):
...     print(id(arg), arg)
...     arg.append(1)
...
py> x = []
py> example(x)
3081877196 []


But with the default argument, you get the same list each time:

py> example()
3081877100 []
py> example()
3081877100 [1]
py> example()
3081877100 [1, 1]
py> example()
3081877100 [1, 1, 1]


-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list