Python Modify Outer Scope (Non Global) Variable

Jul 18, 2019
global_var = 1def 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] # listdef 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]}")

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.