0

I thought I had learn python and that parameters/arguments (which is the correct term?) were just local variables within the method and if they were not declared in the method call then they would take their defined default values. This example clearly shows that I'm wrong:

This code

def example(foo=[]):
    print foo
    bar = 'Hello world'
    foo.append(bar)
    return foo

print example()
print example()

prints out this

[]
['Hello world']
['Hello world']
['Hello world', 'Hello world']

I would have expected it to print out:

[]
['Hello world']
[]
['Hello world']

Why doesn't that happen _?


I know that

print example([])
print example([])

prints what I expect. But that kinda miss the point of having default values..

Bonus info: Using Python 2.7.3 and IPython

Norfeldt
  • 8,272
  • 23
  • 96
  • 152

1 Answers1

2

Default values for arguments are created only once per method, at the time of its definition, not use, which causes trouble (or at least not entirely straight forward behaviour) with mutable values.

To get what you expect, you'll have to create it inside the function instead, something like;

def example(foo=None):
    if foo is None: foo = []
    print foo
    bar = 'Hello world'
    foo.append(bar)
    return foo
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
  • You are absolutely right! I just found this that backs your answer up http://www.deadlybloodyserious.com/2008/05/default-argument-blunders/ – Norfeldt Jul 22 '13 at 07:10