Last active
August 29, 2015 13:57
-
-
Save yangshun/9839578 to your computer and use it in GitHub Desktop.
Python Variable Scope Examples
This file contains 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
a = 1 | |
def foo(): | |
print(a) # Prints 1. Accesses the variable a outside its own scope. | |
foo() | |
print(a) # Prints 1. a not modified. | |
b = 2 | |
def bar(): | |
b = 3 # Creates a new variable b within the function scope. | |
print(b) # Prints 3. Accesses the variable within its own scope. | |
bar() | |
print(b) # Prints 2. Printing the variable in the global scope. | |
c = 3 | |
def foobar(): | |
c = c + 1 # UnboundLocalError: local variable 'c' referenced before assignment. | |
# Python treats this like d = d + 1; it is unable to find d in the scope. | |
print(c) | |
foobar() # Comment out this line to skip the crash. | |
d = 4 | |
def barfoo(): | |
global d # Cannot use nonlocal d. nonlocal only accesses parent function variables. | |
# For barfoo, there is no parent function. | |
d = 5 # Modifies the global variable d | |
print(d) # Prints 5. Local variable d is the same as the one in the global scope. | |
barfoo() | |
print(d) # Prints 5. Global variable d was modified within barfoo() | |
def outer(): | |
e = 5 | |
def inner(): | |
nonlocal e # Can use nonlocal now to refer to variable in the parent function. | |
e += 1 | |
print(e) | |
return inner | |
in_test = outer() | |
in_test() # Prints 6. | |
in_test() # Prints 7. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment