[Python-Dev] Simpler finalization semantics (was Re: PEP 343 -Abstract Block Redux)

Michael Chermside mcherm at mcherm.com
Wed May 18 19:02:25 CEST 2005


[I apologize in advance if this sounds a bit disjointed... I started
to argue one thing, but by the end had convinced myself of the
opposite, and I re-wrote the email to match my final conclusion.]

Guido writes:
> About deleting VAR I have mixed feelings. [...]
> I think that, given that we let the for-loop variable survive, we
> should treat the with-statement variable the same way.

We said the same thing about the variable in list comprehensions
and it's now obvious that it should NEVER have been allowed to escape
it's scope. But the key difference is that list comprehensions are
EXPRESSIONS, and for and 'with' are STATEMENTS. Expressions shouldn't
modify the local environment, statements often do.

Of course, that argument _permits_ not deleting VAR, but doesn't
recomend in favor of it.

My first thought for ideal behavior was that if VAR was previously
defined (eg: a global, an existing attribute of some object, etc),
then it should not be 'del''ed afterward. But VAR was newly created
by the 'with' statement then we WOULD del it to keep the namespace
"neat". Trouble is, that's FAR too complex, and depends on a
distinction Python has not used before (although it's nearly the
same as the property that controls the meaning of globally declared
variables).

My next thought was to just allow 'with' statements to introduce
their own "scope"... the meaning that the VAR variable takes on within
a 'with' statement is not propogated outside the scope of the statement.
But imagine trying to implement this in CPython... don't forget details
like supporting locals(). If it's too hard to do, then it's probably
not the right solution.

So then I thought "Well, what's the harm in letting the variable
survive the 'with' statement?" I'm a big fan of keeping namespaces
"clean", but it's just not important enough to incurr other penalties.
So in this case, I (reluctantly, after giving myself quite a talking-to)
favor having the 'with' statement with VAR create said variable in the
appropriate scope as a side-effect, much like 'for'.

-- Michael Chermside



More information about the Python-Dev mailing list