global declaration from within functions

Terry Reedy tjreedy at home.com
Wed Aug 15 15:23:56 EDT 2001


"Rob Andrews" <rob at jam.rr.com> wrote in message
news:3B7A87D8.6F75B13F at jam.rr.com...
>I'm trying to think of  *why* one might want to
> declare or modify a global from within a function.

Alex gave one example.  Another is a recursive function that need
initialization.

def recursive(n)
  res = []
  global __recurse # use name *unlikely* to conflict
  def __recurse(i, respend = res.append)
    respend(<expression involving i>
    if i: __recurse(i-1)
  __recurse(n)
  return res

Here, both the use of global and the default argument hack are
substitutes for the new nested scoping rule, which lets the above be
writen more naturally as

def recursive(n)
  res = []
  respend = res.append
  def inner_recurse(i)
    respend(<expression involving i>
    if i: inner_recurse(i-1)
  inner_recurse(n)
  return res

This is one use of global that will disappear as people upgrade.

Terry J. Reedy








More information about the Python-list mailing list