1

I don't understand why the behavior between func_1 and func_2 are different. Intuitively, I thought both shouldn't work, because memory is initialized each time when the function is called. But apparently there is more to that. And this trick only works for mutable variables (as the list in func_1). What is going on under the hood here?

class RecursiveDemo:
    def func_1(self, memory=[]):
        memory.append("@")
        if len(memory) <= 5:
            self.func_1()
        else:
            print("=== Done ===")

    def func_2(self, memory=0):
        memory += 1
        if memory <= 5:
            self.func_2()
        else:
            print("=== Done ===")

r = RecursiveDemo()
r.func_1() ## Works. Done is printed. 
r.func_2() ## Doesn't work. RecursionError: maximum recursion depth exceeded in comparison
F.S.
  • 1,175
  • 2
  • 14
  • 34
  • 1
    Nothing to do with scope :) The default is not defined "per call" but per function definition and changes to it are reflected over funciton call as you "add" to it. Better do `def func_1(self, memory = None): memory = memory or []` to supply a default empty list or a filled one. so your default [] stacks its values over function calls - the integer is always initted to 0 on call if not given so it never reaches 5 hence the recursion error – Patrick Artner Apr 06 '20 at 07:13
  • 1
    As you can see from the dupe - its a more common "astonishing" thing ppl encounter when delving into python – Patrick Artner Apr 06 '20 at 07:13
  • 1
    Thanks! I tried to google it but I'd never be able to find that dupe link – F.S. Apr 06 '20 at 07:56

0 Answers0