Getting around immutable default arguments for recursion

James Mills prologic at shortcircuit.net.au
Wed Jan 14 17:29:36 EST 2009


On Thu, Jan 15, 2009 at 8:11 AM, dpapathanasiou
<denis.papathanasiou at gmail.com> wrote:
> I wrote this function to retrieve a list of items from a dictionary.
>
> The first time it was called, it worked properly.
>
> But every subsequent call returned the results of the prior call, plus
> the results of the current call.
>
> I was confused until I read in the docs that default arguments are
> immutable.
>
> Is there any way around this, to be able to write recursive functions
> with default arguments?
>
> Here's the code:
>
> def get_prior_versions (item_id, priors=[]):
>    """Return a list of all prior item ids starting with this one"""
>    global history_db # key = item id, value = prior item id
>    prior_id = history_db[item_id]
>    if not prior_id:
>        return priors
>    else:
>        priors.append(prior_id)
>        return get_prior_versions(prior_id, priors)

How about:

def get_prior_versions (item_id, priors=None):
   """Return a list of all prior item ids starting with this one"""
   global history_db # key = item id, value = prior item id
   prior_id = history_db[item_id]
   if not prior_id:
       return priors
   else:
       if priors:
           priors.append(prior_id)
       else:
           priors = [prior_id]
       return get_prior_versions(prior_id, priors)



More information about the Python-list mailing list