Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from inspect import currentframe
- import ctypes
- __all__ = ['slots']
- PyFrame_LocalsToFast = ctypes.pythonapi.PyFrame_LocalsToFast
- PyFrame_LocalsToFast.argtypes = [ctypes.py_object, ctypes.c_int]
- PyFrame_LocalsToFast.restype = None
- class SlotContext(object):
- def __init__(self, datum, frame):
- self._datum = datum
- self._frame = frame
- self._g_update = {}
- self._g_add = []
- self._l_update = {}
- def __enter__(self):
- _globals = self._frame.f_globals
- _locals = self._frame.f_locals
- for key, val in self._datum.iteritems():
- if key in _locals:
- self._l_update[key] = _locals[key]
- _locals[key] = val
- elif key in _globals:
- self._g_update[key] = _globals[key]
- _globals[key] = val
- else:
- self._g_add.append(key)
- _globals[key] = val
- # black magic
- PyFrame_LocalsToFast(self._frame, 0)
- def __exit__(self, type, value, traceback):
- _globals = self._frame.f_globals
- _locals = self._frame.f_locals
- for key, val in self._g_update.iteritems():
- _globals[key] = val
- for key in self._g_add:
- del _globals[key]
- for key, val in self._l_update.iteritems():
- _locals[key] = val
- # black magic
- PyFrame_LocalsToFast(self._frame, 0)
- # avoid possible memory leaks
- del self._frame
- # XXX check me
- if type is None:
- return True
- def slots(datum):
- # Get caller frame using black magic
- frame = currentframe().f_back
- return SlotContext(datum, frame)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement