title: ContextManager accessing the locals() of the calling with block
body: <p>I'm trying to write a multi-threading helper with context managers. The idea is to define a bunch of functions inside a block and the context manager 'magically' takes care of the scheduling and everything. A simplified, working version looks like this:</p>
  
  <pre><code>import contextlib
  
  @contextlib.contextmanager
  def multi_threaded(count):
      funcs = []
      yield funcs
      my_slice = int(count / len(funcs))
      for i, func in enumerate(funcs):
          start = my_slice * i
          func(start, start + my_slice)   
  
  
  def spawn_many():
      dataset = [1, 2, 3, 4, 5]
      with multi_threaded(len(dataset)) as mt:
          def foo(start_idx, end):
              print("foo" + str(dataset[start_idx : end]))
          def bar(start_idx, end):
              print("bar" + str(dataset[start_idx : end]))
          mt.append(foo)
          mt.append(bar)
  
  spawn_many()
  </code></pre>
  
  <p>This example works, but I'd like to get rid of these lines:</p>
  
  <pre><code>        mt.append(foo)
          mt.append(bar)
  </code></pre>
  
  <p>So that the user only needs to define the functions without adding them to the collection. Why? Because it's less error prone and I won't have control of the code that gets written with this library.</p>
  
  <p>The problem is that after the yield I'm out of the scope where the <code>def foo</code> happened so I have no knowledge of the <code>locals()</code> existing in that scope, which is basically what I need to know which functions got defined in there. Any ideas/tricks/words of encouragement?</p>
  
  <p>Thanks for reading!</p>