default method parameter behavior

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • jianbing.chen@gmail.com

    #1

    default method parameter behavior

    I ran into a similar situation like the following (ipython session).
    Can anyone please explain why the behavior?
    Thanks in advance.

    In [11]: def foo(b=[]):
    ....: b.append(3)
    ....: return b
    ....:

    In [12]: foo()
    Out[12]: [3]

    In [13]: foo()
    Out[13]: [3, 3]

    In [14]: foo([])
    Out[14]: [3]

    In [15]: foo([])
    Out[15]: [3]
  • Konstantin Veretennicov

    #2
    Re: default method parameter behavior

    On Wed, Apr 2, 2008 at 10:59 PM, <jianbing.chen@ gmail.comwrote:
    I ran into a similar situation like the following (ipython session).
    Can anyone please explain why the behavior?
    Of course.
    Default parameter values are evaluated when the function definition is
    executed. This means that the expression is evaluated once, when the
    function is defined, and that that same ``pre-computed'' value is used
    for each call. This is especially important to understand when a
    default parameter is a mutable object, such as a list or a dictionary:
    if the function modifies the object (e.g. by appending an item to a
    list), the default value is in effect modified.

    --
    kv

    Comment

    • Jerry Hill

      #3
      Re: default method parameter behavior

      On Wed, Apr 2, 2008 at 3:59 PM, <jianbing.chen@ gmail.comwrote:
      I ran into a similar situation like the following (ipython session).
      Can anyone please explain why the behavior?
      Contents: General Python FAQ- General Information- What is Python?, What is the Python Software Foundation?, Are there copyright restrictions on the use of Python?, Why was Python created in the fi...


      Since you got bitten by this, you may also find it useful to take a
      look at one of the pages that talks about common python problems, like
      http://zephyrfalcon.org/labs/python_pitfalls.html or
      http://www.ferg.org/projects/python_gotchas.html (both of which
      mention the problems with mutable default arguments).

      --
      Jerry

      Comment

      Working...