Skip to content

Instantly share code, notes, and snippets.

@jsbueno
Created December 8, 2015 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsbueno/ea9d304e702553c38278 to your computer and use it in GitHub Desktop.
Save jsbueno/ea9d304e702553c38278 to your computer and use it in GitHub Desktop.
File sketch to implement a "nonlocals()" call in Python 3.x (analog to "globals()" and "locals()" )
import sys
from collections.abc 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
print(b)
return c, d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment