D
dpapathanasiou
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)
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)