Is it possible to modify a variable in python that is in an outer (enclosing), but not global, scope?

On Python 3, use the nonlocal keyword:

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.

def foo():
    a = 1
    def bar():
        nonlocal a
        a = 2
    bar()
    print(a)  # Output: 2

On Python 2, use a mutable object (like a list, or dict) and mutate the value instead of reassigning a variable:

def foo():
    a = []
    def bar():
        a.append(1)
    bar()
    bar()
    print a

foo()

Outputs:

[1, 1]

Leave a Comment