Created
November 18, 2023 21:36
-
-
Save thomasahle/c24b91f2bb19e853cc5ae58cf263b14a to your computer and use it in GitHub Desktop.
Test of nonlocals functions
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
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