Python overwriting variables in nested functions [duplicate]

In Python 3.x, you can use the nonlocal keyword:

def outer():
    string = ""
    def inner():
        nonlocal string
        string = "String was changed by a nested function!"
    inner()
    return string

In Python 2.x, you could use a list with a single element and overwrite that single element:

def outer():
    string = [""]
    def inner():
        string[0] = "String was changed by a nested function!"
    inner()
    return string[0]

Leave a Comment