Modifying the default argument of function

Chris Angelico rosuav at gmail.com
Tue Jan 21 14:46:16 EST 2014


On Wed, Jan 22, 2014 at 6:36 AM, Mû <mu-- at melix.net> wrote:
> These were clear and quick answers to my problem. I did not think of this
> possibility: the default argument is created once, but accessible only by
> the function, therefore is not a global variable, whereas it looks like if
> it were at first glance.

You can actually poke at the function a bit and see what's happening.
Try this in the interactive interpreter:

>>> def f(x=[2,3]):
    x.append(1)
    return x

>>> f()
[2, 3, 1]
>>> f()
[2, 3, 1, 1]
>>> f.__defaults__
([2, 3, 1, 1],)

The __defaults__ attribute of a function is a tuple of its parameter
defaults. You can easily see there that the list has changed as you
changed it in the function. You could check it with id() or is, too:

>>> id(f.__defaults__[0])
24529576
>>> id(f())
24529576
>>> f() is f.__defaults__[0]
True

ChrisA



More information about the Python-list mailing list