[Python-ideas] adding an __exec__ method to context managers?

Carl Johnson cmjohnson.mailinglist at gmail.com
Tue Oct 13 05:09:06 CEST 2009

This is definitely an idea that python-ideas has seen before. Just a
couple months ago, when the syntax of "with" was being changed to
allow for "with a, b, c" this was kicked around as a possible
improvement to the with statement.

Taking a step back, it seems like what you really want is some easy
way to create callbacks, just like Ruby blocks or the new Objective-C
blocks. There are a number of ways this could be done:

1. Some kind of multiline lambda. (This is generally considered to be

2. Relaxing the restrictions on decorators so that, eg. this, is legal:

 def _(mt):

    for i in mt.iter:


       with mt.critical:

Then you can have it auto-call itself and ignore the fact that _ will
be the result (presumably None) and not a callable.

3. Some sort of "out of order operation" signal, as was batted around
on the list a while back:

result = pymp.parallel_for( ~~DEFINE_ME_NEXT~~, range(100))
def DEFINE_ME_NEXT(mt): ...

There are many potential ways to spell that.

4. Some modification to the "with" statement, as you are proposing.
The resistance that you will face with this idea is that it is
significantly different from how "with" works now, since it does not
create a block at all.

Frankly I think this list is going to face proposals for some block
substitute or another every couple months between now and whenever
Python finally allows for some more readable way of passing functions
to other functions.

— Carl Johnson

More information about the Python-ideas mailing list