Python Modify Outer Scope (Non Global) Variable

July 18, 2019
global_var = 1

def test():
    outer_var = 1

    def _test():
        global global_var
        nonlocal outer_var

        global_var = 2
        outer_var = 2
        local_var = 2

    _test()
    print(f"global_var={global_var}, outer_var={outer_var}")
global_var=2, outer_var=2

To avoid using keyword like global or nonlocal, you can access variable via list or dict or Object.

global_var = [1] # list

def test():
    outer_var = {0: 1} # dict


    def _test():
        global_var[0] = 2
        outer_var[0] = 2

    _test()
    print(f"global_var={global_var[0]}, outer_var={outer_var[0]}")
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.