bossylobster

Python Monkey Patching Function Globals

Jan 2nd, 2013
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.63 KB | None | 0 0
  1. class GlobalCaller(object):
  2.  
  3.   def __init__(self, method, value):
  4.     self.method = method
  5.     self.value = value
  6.  
  7.   def __call__(self, *args, **kwargs):
  8.     added = False
  9.     curr_globals = self.method.func_globals
  10.     if 'a' not in curr_globals:
  11.       curr_globals['a'] = self.value
  12.       added = True
  13.     result = self.method(*args, **kwargs)
  14.     if added:
  15.       curr_globals.pop('a')
  16.     return result
  17.  
  18.  
  19. def deco(value):
  20.  
  21.   def actual_deco(method):
  22.  
  23.     return GlobalCaller(method, value)
  24.  
  25.   return actual_deco
  26.  
  27.  
  28. @deco(99)
  29. def f():
  30.   return a
  31.  
  32.  
  33. @deco(9)
  34. def g(b):
  35.   return a + b
  36.  
  37.  
  38. print f()
  39. print g(1)
Advertisement
Add Comment
Please, Sign In to add comment