document.write('
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. # -*- coding: utf-8 -*-
  2. # Author: João S. O. Bueno
  3. # License: Creative Commons Attribution 3.0
  4. # http://creativecommons.org/licenses/by/3.0/
  5.  
  6. from inspect import currentframe
  7. from types import FunctionType
  8.  
  9.  
  10. def caller_variables(func):
  11.     """A decorator that makes the local variables on the caller function
  12.    available as Free Variables on the called function.
  13.    Creates the possibility for differente ways of thinking about scope
  14.    when coding
  15.  
  16.     Warning: Decoration order matters for this decorator: it should be the outermost one
  17.     Until introspection allows one to find out our way in decorated functions
  18.     (expected for Python 3.2)
  19.    """
  20.    
  21.     def new_func(*args, **kw):
  22.         caller_vars = currentframe(1).f_locals
  23.        
  24.         #now, recreate the decorated function as a new function,
  25.         # so that it has the local variables from the caller
  26.         # scope as its global variables:
  27.        
  28.         new_globals = func.func_globals.copy()
  29.         new_globals.update(caller_vars)
  30.        
  31.         # and recreate the called functions, updating only the global dict
  32.         # so that variables from the calling scope apear to be global variables
  33.         # to it.
  34.         reforged_func = FunctionType(func.func_code, new_globals, func.func_name,
  35.                                      func.func_defaults, func.func_closure)
  36.         return reforged_func(*args, **kw)
  37.     return new_func
  38.  
  39.  
  40. if __name__ == "__main__":
  41.     ##
  42.     ## test
  43.     ##
  44.  
  45.     self = "this should not be printed"
  46.  
  47.     @caller_variables
  48.     def a():
  49.         print self
  50.  
  51.     def b():
  52.         self = "This should be printed."
  53.         a()
  54.  
  55.     b()
  56.  
  57.     class C(object):
  58.         def __init__(self):
  59.             a()
  60.         def __repr__(self):
  61.             return "And this as well."
  62.  
  63.     c = C()
');