[Python-ideas] if with as

Sam free.condiments at gmail.com
Mon Mar 5 20:37:06 CET 2007


(apologies to Larry - the GMail interface is still confusing and arbirary)

On 05/03/07, Larry Hastings <larry at hastings.org> wrote:
> I like it too.  However: unlike "except x as e" and "with a as b", the
> indented blocks under if and else don't establish a new scope.  So it
> begs the question: what is the lifetime of the variable created by "if x
> as y" here?  If it magically goes away, even as you create new variables
> in the scope, that just seems a little too weird to me.  If it outlives
> the nested block under the if, that's weird too.

I could be using a different definition of 'scope' than you, but:

>>> try:
       raise Exception("foo")
except Exception, e:
       pass
>>> print e
foo

seems to suggest that except blocks don't set up a new scope to me.

>>> with file('C:/foo.txt') as f:
       pass

>>> print f
<closed file 'C:/foo.txt', mode 'r' at 0x00B98800>

says the same thing about the with statement to me.

So the variable defined with an if <expr> as <name>: statement
outliving the end of the indented block would be absolutely no
surprise according to the current semantics of other statements.

--Sam



More information about the Python-ideas mailing list