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


Asked By – grigoryvp

Consider this example:

def A():
    b = 1
    def B():
        # I can access 'b' from here.
        # But can i modify 'b' here?

For the code in the B function, the variable b is in a non-global, enclosing (outer) scope. How can I modify b from within B? I get an error if I try it directly, and using global does not fix the problem since b is not global.

Python implements lexical, not dynamic scope – like almost all modern languages. The techniques here will not allow access to the caller’s variables – unless the caller also happens to be an enclosing function – because the caller is not in scope. For more on this problem, see How can I access variables from the caller, even if it isn’t an enclosing scope (i.e., implement dynamic scoping)?.

Now we will see solution for issue: 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
    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():
    print a



[1, 1]

This question is answered By – Adam Wagner

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0