0

Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument

Am I missing something here or is this really a bug? Below is a recursive function that generates a multi-dimensional list from a tuple specification, for example.

dim((2,3))  
returns  
[[[],[],[]],[[],[],[]]]

The only problem is that it adds to the list each time I call it, if I call it without the default parameter, if I specify the default parameter like dim((2,3),[]), then it's fine. It's saving the state of the default parameter each call! If no one can find a problem with what I'm doing I'll enter it in the python bug reporter.

cdr = lambda l : l[1:]
car = lambda l : l[0]
last = lambda x : x[-1:][0]


def dim(t, c = []):
    if len(t) > 0:
        i = car(t)
        for j in range(i):
            c.append([])
            dim(cdr(t), last(c))
    return c


print dim([2,3])
print dim([2,3])
print dim([2,3])
print dim([2,3])
Community
  • 1
  • 1

1 Answers1

0

def dim(t, c = [])

It's a bug (in your code). That c = [] part is only evaluated once during the entire program. When you call dim, c is being continuously appended to. A better approach would be this:

def dim(t, c=None):
    if c is None:
        c = []
    ...
Chris Eberle
  • 47,994
  • 12
  • 82
  • 119
  • Exactly. But to nitpick, `is` is preferred for comparisions with singletons (most notable, of course, `None`) - i.e. `s/if c == None/if c is None/`. –  May 09 '11 at 15:29