Skip to content

Instantly share code, notes, and snippets.

@thomasahle
Created November 18, 2023 21:36
Show Gist options
  • Save thomasahle/c24b91f2bb19e853cc5ae58cf263b14a to your computer and use it in GitHub Desktop.
Save thomasahle/c24b91f2bb19e853cc5ae58cf263b14a to your computer and use it in GitHub Desktop.
Test of nonlocals functions
def nonlocals():
import inspect
stack = inspect.stack()
if len(stack) < 3: return {}
f = stack[2][0]
res = {}
while f.f_back:
res.update({k:v for k,v in f.f_locals.items() if k not in res})
f = f.f_back
return res
def f():
x = 3
def g():
print('x' in nonlocals())
return g
f()() # Prints True
def nonlocals():
import inspect
caller = inspect.currentframe().f_back
return {k: v for k, v in caller.f_locals.items() if k in caller.f_code.co_freevars}
def f():
x = 3
def g():
print('x' in nonlocals())
return g
f()() # Prints False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment