Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's one way:</p> <pre><code>from __future__ import with_statement import inspect class button(object): def __enter__(self): # keep track of all that's already defined BEFORE the `with` f = inspect.currentframe(1) self.mustignore = dict(f.f_locals) def __exit__(self, exc_type, exc_value, traceback): f = inspect.currentframe(1) # see what's been bound anew in the body of the `with` interesting = dict() for n in f.f_locals: newf = f.f_locals[n] if n not in self.mustignore: interesting[n] = newf continue anf = self.mustignore[n] if id(newf) != id(anf): interesting[n] = newf if interesting: print 'interesting new things: %s' % ', '.join(sorted(interesting)) for n, v in interesting.items(): if isinstance(v, type(lambda:None)): print 'function %r' % n print v() else: print 'nothing interesting' def main(): for i in (1, 2): def ignorebefore(): pass with button(): def testing(i=i): return i def ignoreafter(): pass main() </code></pre> <p><strong>Edit</strong>: stretched code a bit more, added some explanation...:</p> <p>Catching caller's locals at <code>__exit__</code> is easy -- trickier is avoiding those locals that were already defined <em>before</em> the <code>with</code> block, which is why I added to main two local functions that the <code>with</code> should ignore. I'm not 100% happy with this solution, which looks a bit complicated, but I couldn't get equality testing correct with either <code>==</code> or <code>is</code>, so I resorted to this rather complicated approach.</p> <p>I've also added a loop (to make more strongly sure the <code>def</code>s before / within / after are being properly handled) and a type-check and function-call to make sure the right incarnation of <code>testing</code> is the one that's identified (everything seems to work fine) -- of course the code as written only works if the <code>def</code> inside the <code>with</code> is for a function callable without arguments, it's not hard to get the signature with <code>inspect</code> to ward against that (but since I'm doing the call only for the purpose of checking that the right function objects are identified, I didn't bother about this last refinement;-).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload