[Python-ideas] Anonymous blocks (again):
Juancarlo Añez
apalala at gmail.com
Mon May 13 23:35:17 CEST 2013
Just a reminder of why I started this discussion.
I couldn't find a way to have:
with context():
do_this()
do_that()
in which the embedded block would be executed multiple times, through
yield. My fault! Lack of understanding about the context manager protocol.
It is not possible to yield to the block multiple times because an
exception within the block will exit the context no matter what __exit__()
does.
Adding new syntax is the kill-all way of things, but I think that it may be
possible to achieve what I think is reasonable by adding to the context
manager protocol.
Perhaps I should just settle for something like:
with context() as c:
white True:
with c.inner():
do_this()
do_that()
But that has the problem that the context manager protocol forces try:
finally: to be spread between __enter__() and __exit__().
The best solution I've seen so far doesn't require any changes:
with context() as c:
@c
def _():
do_this()
do_that()
Make the decorator remember the decorated function, and let __exit__() do
the iteration. The only problem with that is that the stack trace for an
exception would be weird.
That's why I thought of new syntax:
within context() as c:
do_this()
do_that()
Python would def the anonymous block, and pass it to a __do__(block) method
in the context. That wouldn't allow passing parameters to the anonymous
block, but the block can use the context (c), and the variables over which
it has visibility.
All that said, I'm happy with how things work now, except for the need to
come up with synthetic names for what should be anonymous functions.
Cheers,
--
Juancarlo *Añez*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130513/bb4f5a3a/attachment.html>
More information about the Python-ideas
mailing list