This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Strange behaviour with default list argument
Type: behavior Stage: resolved
Components: Versions: Python 3.2, Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: barry, bsdphk, eric.smith
Priority: normal Keywords:

Created on 2013-06-03 19:38 by bsdphk, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (3)
msg190557 - (view) Author: Poul-Henning Kamp (bsdphk) Date: 2013-06-03 19:38
I'd like to nominate this piece of code as candidate for the next round of "Most unexpected python behaviour" awards:

    def foo(a, x = []):
        x.append(a)
        return x

    print(foo(1))
    print(foo(2))

I expected the output to be:
    [1]
    [2]
but I get:
    [1]
    [1, 2]

Bug?  (If not, I'd *love* to read the rationale for this behaviour...)
msg190558 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2013-06-03 19:58
It's by design. Search for "mutable default arguments", for example http://docs.python-guide.org/en/latest/writing/gotchas.html#mutable-default-arguments
msg190566 - (view) Author: Barry A. Warsaw (barry) * (Python committer) Date: 2013-06-03 21:07
While it's true that it can be confusing to users, it's not a bug.

http://docs.python.org/2/reference/compound_stmts.html#function

and a nice treatise on the subject by the Effbot:

http://effbot.org/zone/default-values.htm
History
Date User Action Args
2022-04-11 14:57:46adminsetgithub: 62327
2013-06-03 21:07:40barrysetnosy: + barry
messages: + msg190566
2013-06-03 19:58:45eric.smithsetstatus: open -> closed

nosy: + eric.smith
messages: + msg190558

resolution: not a bug
stage: resolved
2013-06-03 19:38:11bsdphkcreate