Created
February 8, 2011 11:43
-
-
Save DmitrySoshnikov/816304 to your computer and use it in GitHub Desktop.
Modification of external vars in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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