Globals in nested functions

Neil Cerutti horpner at yahoo.com
Thu Jun 21 14:48:19 EDT 2007


On 2007-06-21, jm.suresh at no.spam.gmail.com <jm.suresh at gmail.com> wrote:
> def f():
>     a = 12
>     def g():
>         global a
>         if a < 14:
>             a=13
>     g()
>     return a
>
> print f()
>
> This function raises an error. Is there any way to access the a
> in f() from inside g().
>
> I could find few past discussions on this subject, I could not
> find the simple answer whether it is possible to do this
> reference.

Python's scoping rules don't allow this. But you can 'box' the
value into a list and get the intended effect.

def f():
  a = [12]
  def g():
    if a[0] < 14:
      a[0] = 13
  g()
  return a[0]

You'll get better results, in Python, by using a class instances
instead of closures. Not that there's anything wrong with Python
closures, but the scoping rules make some fun tricks too tricky.

-- 
Neil Cerutti



More information about the Python-list mailing list