Getting around immutable default arguments for recursion
dpapathanasiou
denis.papathanasiou at gmail.com
Wed Jan 14 18:27:01 EST 2009
> How about this then:
>
> 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:
> if priors:
> return priors or []
> else:
> if priors:
> priors.append(prior_id)
> else:
> priors = [prior_id]
> return get_prior_versions(prior_id, priors)
Without the "if priors:" line just above the first return statement (a
typo perhaps?), then yes, it would do what I want.
> a) a global should and need not be used.
Passing the entire dictionary to every function that accesses it is
better?
> b) this function could be rewritten without recursion.
Right, any recursive function can be written iteratively and vice-
versa. I'm not sure that makes it "bad".
More information about the Python-list
mailing list