fork download
  1. import sys
  2. import copy
  3. import types
  4. from inspect import isfunction
  5.  
  6. class UsingHolder:
  7. def __init__(self, frame, old_locals):
  8. self.frame = frame
  9. self.old_locals = old_locals
  10.  
  11. def __enter__(self):
  12. print 'Using is entered'
  13.  
  14. def __exit__(self, type, value, tb):
  15. for local in self.frame.f_locals.keys():
  16. if local not in self.old_locals:
  17. del self.frame.f_locals[local]
  18.  
  19. print 'Using holder is deleted'
  20.  
  21. def using(o):
  22. frame = sys._getframe().f_back
  23. old_locals = copy.copy(frame.f_locals)
  24.  
  25. frame.f_locals.update(o.__dict__)
  26. for n, f in o.__class__.__dict__.items():
  27. if isfunction(f):
  28. frame.f_locals[n] = lambda *args, **kwargs: f(o, *args, **kwargs)
  29.  
  30. return UsingHolder(frame, old_locals)
  31.  
  32. class A:
  33. def __init__(self):
  34. self.i = 10
  35.  
  36. def f(self, j):
  37. print self.i, j
  38.  
  39. @staticmethod
  40. def g():
  41. pass
  42.  
  43. def do_something():
  44. a = A()
  45. with using(a):
  46. exec('')
  47. f(20)
  48.  
  49. do_something()
  50.  
Success #stdin #stdout 0.06s 9008KB
stdin
Standard input is empty
stdout
Using is entered
10 20
Using holder is deleted