Advertisement
Guest User

black magic

a guest
May 14th, 2013
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.72 KB | None | 0 0
  1. from inspect import currentframe
  2. import ctypes
  3.  
  4.  
  5. __all__ = ['slots']
  6.  
  7.  
  8. PyFrame_LocalsToFast = ctypes.pythonapi.PyFrame_LocalsToFast
  9. PyFrame_LocalsToFast.argtypes = [ctypes.py_object, ctypes.c_int]
  10. PyFrame_LocalsToFast.restype = None
  11.  
  12.  
  13. class SlotContext(object):
  14.     def __init__(self, datum, frame):
  15.         self._datum = datum
  16.         self._frame = frame
  17.         self._g_update = {}
  18.         self._g_add = []
  19.         self._l_update = {}
  20.  
  21.     def __enter__(self):
  22.         _globals = self._frame.f_globals
  23.         _locals = self._frame.f_locals
  24.  
  25.         for key, val in self._datum.iteritems():
  26.             if key in _locals:
  27.                 self._l_update[key] = _locals[key]
  28.                 _locals[key] = val
  29.             elif key in _globals:
  30.                 self._g_update[key] = _globals[key]
  31.                 _globals[key] = val
  32.             else:
  33.                 self._g_add.append(key)
  34.                 _globals[key] = val
  35.  
  36.         # black magic
  37.         PyFrame_LocalsToFast(self._frame, 0)
  38.  
  39.     def __exit__(self, type, value, traceback):
  40.         _globals = self._frame.f_globals
  41.         _locals = self._frame.f_locals
  42.  
  43.         for key, val in self._g_update.iteritems():
  44.             _globals[key] = val
  45.  
  46.         for key in self._g_add:
  47.             del _globals[key]
  48.  
  49.         for key, val in self._l_update.iteritems():
  50.             _locals[key] = val
  51.  
  52.         # black magic
  53.         PyFrame_LocalsToFast(self._frame, 0)
  54.  
  55.         # avoid possible memory leaks
  56.         del self._frame
  57.  
  58.         # XXX check me
  59.         if type is None:
  60.             return True
  61.  
  62.  
  63. def slots(datum):
  64.     # Get caller frame using black magic
  65.     frame = currentframe().f_back
  66.  
  67.     return SlotContext(datum, frame)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement