[Tutor] Recursive search

Corran Webster cwebster@nevada.edu
Thu, 13 Apr 2000 07:44:52 -0700


> In your code I didn't see any line like
> 	configs.append( file )
>
>
> Additionally, the list is a local variable for the function.  That means
> that each call to the function will have its own version of configs.
> You want to share it in some way so that all of the files will be in the
> same list.  It would probably be best to add it as an argument to the
> function.
>
> def getConfigs( file, configs = [] ):
> 	...
>
> Then pass configs to the recursive function call.  I used a default
> argument here so the first time the function is called by the client,
> the list will be initialized to the empty list.

This won't work the way you expect because of Python's mutable default
argument gotcha.  To see why, consider the following code which attempts to
append an item to a list, or create a new list if no list is passed:

>>> def f(n, spam = []):
...   spam.append(n)
...   return spam
...
>>> foo = f(1)
>>> print foo
[1]
>>> bar = f(2)
>>> print bar   # uh-oh!
[1, 2]
>>> print foo   # even worse!
[1, 2]
>>> print f.func_defaults  # this is the culprit
([1, 2],)

This is because python variables are references to objects, and in this
case all  the variables spam, foo and bar refer to the same list (the one
in f.func_defaults).  Changing any one will change all the others

The standard way to avoid this sort of problem is to do something like:

def getConfigs(file, configs = None):
    if configs is None: configs = []
    ...

This ensures that a new list is created if only one argument is passed in.


Regards,
Corran