Getting around immutable default arguments for recursion

James Mills prologic at shortcircuit.net.au
Thu Jan 15 00:04:07 CET 2009


On Thu, Jan 15, 2009 at 8:32 AM, dpapathanasiou
<denis.papathanasiou at gmail.com> wrote:
(...)

> It's not exactly right for what I'm doing, b/c the caller always
> expects a list in return.

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)

By the way, this is a really badly
written function for 2 reasons:

a) a global should and need not be used.
b) this function could be rewritten without recursion.

cheers
James



More information about the Python-list mailing list