[Python-ideas] A different kind of context manager

Chris Angelico rosuav at gmail.com
Mon Oct 21 16:41:16 CEST 2013


On Tue, Oct 22, 2013 at 12:55 AM, Kristján Valur Jónsson
<kristjan at ccpgames.com> wrote:
> This sort of thing would need compiler and syntax support, of course.  The
> compiler would need to create an anonymous function object.   The return
> value out of "code" would be some token that could be special if the code
> returned....

Possible problem: A function creates a new scope, a with block
doesn't. Imagine this:

with different_tasklet():
  foo = 1
print(foo)

In current Python, whatever different_tasklet does, those two foos are
the same foo. If the body becomes a callable, that could get messy. Do
you have to declare 'nonlocal foo'  when you enter the with block?
That'd be a nasty backward-compatibility break. Or is this callable
somehow part of the previous scope? Could work in theory, but would
need a fair amount of magic.

ChrisA


More information about the Python-ideas mailing list