[Python-Dev] 'With' context documentation draft (was Re: Terminology for PEP 343
Walter Dörwald
walter at livinglogic.de
Fri Jul 8 13:39:44 CEST 2005
Guido van Rossum wrote:
> On 7/7/05, Walter Dörwald <walter at livinglogic.de> wrote:
>
>>What is still unspecified (or at least not explicitely mentioned) in
>>the PEP is the lifetime of VAR in:
>>
>> with EXPR as VAR:
>> BLOCK
>
> It is specified well enough IMO -- you're supposed to take the
> translation into basic Python seriously. That translation specifies a
> simple assignment to VAR, and that's what I meant (and what I'm sure
> most folks understood). IOW VAR lives in the surrounding scope,
> overwrites a previous value, and survives past the with-statement
> (unless it is set inside of course).
Are there use cases for both variants?
If VAR would live only until the end of the with block, this would give
us a nice way of generating nested data structures:
class blist(list):
def __init__(self, parent=None):
if parent:
parent.append(self)
list.__init__(self)
def __enter__(self):
return self
def __call__(self, *items):
self.extend(items)
return self
x = blist()
x(1)
with blist(x) as x:
x(2)
with blist(x) as x:
x(3)
x(4)
x(5)
This would create the list:
[1, [2, [3], 4], 5]
With the current version of PEP 343, we would either have to use
different variable names on each level or use a global stack where
__enter__() and __exit__() push and pop values.
Bye,
Walter Dörwald
More information about the Python-Dev
mailing list