Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
File sketch to implement a "nonlocals()" call in Python 3.x (analog to "globals()" and "locals()" )
import sys
from import MutableMapping
class DictFilteredView(MutableMapping):
def __init__(self, viewed, allowed):
self.viewed = viewed
self.allowed = set(allowed)
def __getitem__(self, item):
if not item in self.allowed:
raise KeyError(str(item))
return self.viewed[item]
def __setitem__(self, item, other):
if not item in self.allowed:
raise KeyError(str(item))
self.viewed[item] = other
def __delitem__(self, item):
raise NotImplementedError
def __iter__(self):
for key in self.allowed:
if key in self.viewed:
yield self.viewed[key]
def __len__(self):
return len(self.allowed.intersection(self.viewed.keys()))
def nonlocals():
frame = sys._getframe().f_back
return DictFilteredView(frame.f_locals, frame.f_code.co_freevars)
# function for testing the thing on the console:
def a():
b = 0
def c():
nonlocal b
b += 1
e = nonlocals()
import ipdb; ipdb.set_trace()
e["b"] = 5
def d():
nonlocal b
return c, d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment