views:

78

answers:

3

I have a function that calls itself to increment and decrement a stack.

I need to call it a number of times, and I'd like it to work the same way in subsequent calls

but, as expected, it doesn't re-use the default value.

I've read that this is a newbie trap and I've seen suggested solutions, but I haven't been able

to make any solution work.

It would be nice to be able to "fun.reset"

def a(x, stack = [None]):
    print x,'  ', stack
    if x > 5:
        temp = stack.pop()
    if x <=5:
        stack.append(1)
    if stack == []:
        return    
    a(x + 1)

print a(0)
print a(2)  #second call
print a(3)  #third call

I expected this to work, but it doesn't.

print a(0, [None])
print a(2, [None])  #second call
print a(3, [None])  #third call

Can I reset the function to it's initial state?

Any help would be appreciated.

+3  A: 
def a(x, stack = None):
    if stack is None:
        stack = [None]
    ...
Kai
this doesn't work. It just re-initializes stack to [None] as the recursive calls don't pass a value for stack.
Peter Stewart
However I appreciate that you've pointed out the main fault in my reasoning. Thanks
Peter Stewart
Sure, I'm glad that Lukasz brought it home.
Kai
A: 

This problem happens because you modify the default argument, which is mutable. As in Kai's answer, one usually solves this by not modifying the default argument.

Bastien Léonard
+4  A: 

Just pass stack explicitly when doing recursive call:

def a(x, stack=None):
    if stack is None:
        stack = [None]
    ...
    a(x + 1, stack)
Łukasz
That's it. It's obvious now that it's been pointed out to me. Thanks
Peter Stewart