[Python-ideas] A different kind of context manager

Kristján Valur Jónsson kristjan at ccpgames.com
Mon Oct 21 16:50:39 CEST 2013



> -----Original Message-----
> 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.

Well, yes, like I said, it could be a new kind of callable if necessary.  But the scope problem is easily solved using "cell" variables, the same way as closures are implemented today.  The compiler, which is building the anonymous function, makes sure to bind local variables to the parent's scope, using cells.

K



More information about the Python-ideas mailing list