[Python-ideas] A different kind of context manager

Andrew Barnert abarnert at yahoo.com
Mon Oct 21 18:25:52 CEST 2013


On Oct 21, 2013, at 7:50, Kristján Valur Jónsson <kristjan at ccpgames.com> wrote:

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

A paradigm case for with is creating a new variable in a context to use outside of it:

    with open(path) as f:
        rows = list(reader(f))
    for row in rows[1:]:

    with lock:
        connections = self.connections
    for connection in connections:

The compiler would not make rows or connections into a closure variable, but a local. So you'd have to write nonlocal in most with statements.

And if you changed the rules so everything was nonlocal by default in a context function, we'd need a new keyword to declare local variables, which would be (a) very different from the rest of python, and (b) hard to come up with a name for that didn't conflict with thousands of different programs.

> 
> K
> 
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas


More information about the Python-ideas mailing list