Python: re-initialize a function's default value for subsequent calls to the function.

Posted by Peter Stewart on Stack Overflow See other posts from Stack Overflow or by Peter Stewart
Published on 2010-04-01T13:36:24Z Indexed on 2010/04/01 13:43 UTC
Read the original article Hit count: 289

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about python

Related posts about beginner