Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Created February 8, 2011 11:43
Show Gist options
  • Save DmitrySoshnikov/816304 to your computer and use it in GitHub Desktop.
Save DmitrySoshnikov/816304 to your computer and use it in GitHub Desktop.
Modification of external vars in Python
# for closured vars
# we may use `nonlocal` keyword
def foo():
a = 10
b = 20
def bar():
nonlocal b # use parent "b"
a = 20 # create local "a"
b = 40 # modify outer "b"
bar()
print(a, b) # 10, 40
foo()
# this approach won't work in the global scope though
# and to modify global var, we should use directly
# modification of the globals() dict
a = 10
b = 20
def bar():
# nonlocal b -- error
a = 20 # create local "a"
globals()['b'] = 40 # modify outer "b"
bar()
print(a, b) # 10, 40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment