Python closures and replacing surrounding scope
Question: I know when using Groovy closures, I can change the `delegate` on the closure
so function calls made within the closure could be defined externally.

Can I do something similar in Python?

Specifically, if you take the following code:

    
    
    def configure():
      build()
    
    def wrap(function):
      def build():
        print 'build'
    
      function()
    
    wrap(configure)
    

I'd like it to print 'build' (only making changes to `wrap()`).

Some notes:

I don't want to pass functions into `configure()` since there may be a large
number of functions that can be called by `configure()`.

I also don't want to define those globally, because, once again, there may be
a large number of functions that can be called by `configure()` and I don't
want to pollute the global namespace.


Answer: Whether or not is a good way to do this is debatable, but here's a solution
that doesn't modify the global namespace.

    
    
    def configure():
      build()
    
    def wrap(f):
      import new
      def build():
        print 'build'
    
      new.function(f.func_code, locals(), f.func_name, f.func_defaults, f.func_closure)()
    
    wrap(configure)
    

I found it at [How to modify the local namespace in
python](http://stackoverflow.com/questions/1142068/how-to-modify-the-local-
namespace-in-python)

