B14 - variable scopes and lookup
variable scope rules
b = 6
def f1(a):
print(a)
print(b)
b = 9
f1(1)
- when the above code is run,
print(a) is run, but an error is thrown for print(b)
- a variable assigned in the body of a function is local by feature
global b needs to be added in the function to treat b as global
variable lookup logic
- if there is a global
x declaration, x comes from and is assigned to the global variable
x = 10
def func():
print(x)
func() ## 10
- if there is a
nonlocal x declaration, x comes from and is assigned to the x local variable of the nearest surrounding function where x is defined
x = 10
def func():
x = 5
print(x)
func() ## 5
print(x) ## 10
- if
x is a parameter or is assigned a value in the function body, it is a local variable
x = 10
def func(x):
print(x)
func(15) ## 15
- if
x is referenced, but not assigned or a parameter:
- it will be looked up in the local scops of the surrounding function bodies
- if not found in surrounding scopes, it will be read from the module global scope
- if not found in the gloval scope, it will be read from `builtins.dict
def outer():
a = 10
def inner():
print(a) ## a is not assigned in inner, so python looks up in outer
inner()
outer() ## 10