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]}")