Created
December 8, 2015 14:33
-
-
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()" )
This file contains 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
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