Globals in nested functions

Bjoern Schliessmann usenet-mail-0306.20.chr0n0ss at spamgourmet.com
Thu Jun 21 15:45:35 CEST 2007


jm.suresh at no.spam.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().

Yes. Pass it to g when calling the latter and let g return the
result.

def f():
    a = 12

    def g(parm):
        if parm < 14:
            return 13
        else:
            return a

    a = g(a)
    return a

print f()

Strange refactoring though.

Regards,


Björn

-- 
BOFH excuse #400:

We are Microsoft.  What you are experiencing is not a problem; it is
an undocumented feature.




More information about the Python-list mailing list