[Tutor] Accessing local variables from nested functions.

Karl Pflästerer sigurd at 12move.de
Sun Feb 13 12:15:03 CET 2005


On 13 Feb 2005, krzys_kyku at tlen.pl wrote:

> what's the Python way of accessing local variables in nesting functions? For 

The way you want to work with closures the Python way is not to do it
but use a class to hold the state.  That's sometimes sad but true.

> example if I have:
>
> def p():
>   var1 = 3
>   def q():
>      print 'var1 in p is', var1
>   q()
>
> then there's no problem in running such function, but what if I'd like to 
> modify var1 so that the change were vissible in p()?

There's a workaround (but see it only as one; it's not pretty).

def outer ():
    var = [1]
    def inner ():
        var[0] += 1
        return var
    return inner

Now if you call outer it's returns a function which when called changes
the value of var.




   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


More information about the Tutor mailing list