-1

I have a function that iterates over a many levels nested dictionary (arg1) collecting data over each iteration, something like this:

def dummy(arg1, found=[], index=0):
    found.append('xyz')

    for d in arg1:
        dummy(arg1[d], found, index+1)

    return found

My functions work as it's supposte to, the problem is that when I call the function a second time, the found argument keeps the value from the previous function call, i.e. the return value from the second call includes the return values from the previous call. I had to add something like

if index == 0:
   found=list() # restart value

to the beginning of the function to initialize the value of the found argument. Any idea why this happens? is this a bug?

Daniel
  • 139
  • 13

1 Answers1

1

No, it's not a bug; see here

To avoid this, you should do:

def dummy(arg1, found=None, index=0):
    if found is None:
        found = []
    ...

or better yet (see here):

sentinel = object()
def dummy(arg1, found=sentinel, index=0):
    if found is sentinel:
        found = []
    ...
Mustafa Aydın
  • 17,645
  • 4
  • 15
  • 38