Getting around immutable default arguments for recursion
MRAB
google at mrabarnett.plus.com
Wed Jan 14 17:26:06 EST 2009
dpapathanasiou 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=[]):
The usual solution is:
def get_prior_versions (item_id, priors=None):
if priors is None:
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)
More information about the Python-list
mailing list