I understand that in most cases nonlocal and global keywords allow inner functions to have access to either the outer function's variables or overall global variables. But the typical closure examples I've seen usually only nest to 2 levels (e.g. 1 outer and 1 inner function). I'm curious how we can access a variable in the first function scope all the way deep in some nested function scope. I know this type of programming doesn't appear often but I'm curious what the answer is
Please see example below
def pseudo_global(): # layer 1 -- first outer function
a = "global"
def block(): # layer 2
def show_a(): # layer 3
nonlocal a # doesn't do anything here because "a" isn't defined in block() scope
# global a # commented out; nothing prints anyway because refers to global scope
print(a) # free variable error; how can I access layer 1's variable here in layer 3?
show_a()
a = "block"
show_a()
block()
pseudo_global()
nonlocal ainsideblock()function. It printsglobal,block.nonlocalinshow_a(). It's only needed in functions that assign to the variable. References automatically search enclosing scopes.a = "block"theshow_a()function will call this new "a" but is the olda = "global"still there in ourpseudo-global()scope?