Variables in nested functions

Ben Cartwright bencvt at gmail.com
Tue Aug 29 21:02:29 EDT 2006


zero.maxi... at gmail.com wrote:
> Is it possible to change the value of a variable in the outer function
> if you are in a nested inner function?

The typical kludge is to wrap the variable in the outer function inside
a mutable object, then pass it into the inner using a default argument:

def outer():
    a = "outer"
    def inner(wrapa=[a]):
        print wrapa[0]
        wrapa[0] = "inner"
    return inner

A cleaner solution is to use a class, and make "a" an instance
variable.

--Ben




More information about the Python-list mailing list