<div dir="ltr"><div style>Hello,</div><div style><br></div><div style>I've banged my self against the wall, and there simply isn't a pythonic way to make a context manager iterate over the yielded-to block of code.</div>
<div style><br></div><div style>I've had to resource to this in Grako[*]:</div><div style><br></div><div style><div> def block():</div><div> self.rule()</div><div> self.ast['rules'] = self.last_node</div>
<div> closure(block)</div><div><br></div><div style>But what I think would be more pythonic is:</div><div style><br></div><div style><div> closure(<br></div></div></div><blockquote style="margin:0px 0px 0px 40px;border:none;padding:0px">
<div style><div style><div style><div style> def:</div></div></div></div><div style><div style><div style><div style> self.rule()</div></div></div></div><div style><div style><div style><div style> self.ast['rules'] = self.last_node</div>
<div style>)</div></div></div></div></blockquote><div style><div style><div><br></div></div></div><div style>Or, better yet (though I know I can't have it):</div><div style><br></div><div style><div> with positive_closure():<br>
</div></div> self.rule()<br><div style><div style><div style> self.ast['rules'] = self.last_node</div></div></div><div style><div><br></div></div>The thing is that a "closure" needs to call the given block repeatedly, while remaining in control of the context of each invocation. The examples given above would signal the closure to be over with an exception.<div>
<br></div><div>The convoluted handling of exceptions on context manager's __exit__ make it impossible (for me) to construct a context manager that can call the yield-to block several times.</div><div><br></div><div>Anyway, the anonymous def syntax, with or without parameters, is a given, and a solution for many qualms about the Python way of things.</div>
<div><br></div><div>[*] <a href="https://bitbucket.org/apalala/grako">https://bitbucket.org/apalala/grako</a><br><div><br><div class="gmail_extra">-- <br><span style="color:rgb(0,102,0)">Juancarlo </span><b style="color:rgb(0,102,0)">Añez</b>
</div></div></div></div>