[Python-ideas] except expression

Steven D'Aprano steve at pearwood.info
Mon Feb 17 06:29:12 CET 2014


On Mon, Feb 17, 2014 at 08:52:41AM +1100, Chris Angelico wrote:

> Scope of default expressions and 'as'
> -------------------------------------
> 
> In a try/except block, the use of 'as' to capture the exception object creates
> a local name binding, and implicitly deletes that binding in a finally clause.
> As 'finally' is not a part of this proposal (see below), this makes it tricky
> to describe; also, this use of 'as' gives a way to create a name binding in an
> expression context. Should the default clause have an inner scope in which the
> name exists, shadowing anything of the same name elsewhere? Should it behave
> the same way the statement try/except does, and unbind the name? 

I consider that a wart, and would not like to repeat that unless 
absolutely necessary.


> Should it
> bind the name and leave it bound? (Almost certainly not; this behaviour was
> changed in Python 3 for good reason.)

I think the first option is best: avoid letting the "as" name leak out 
into the local scope, just like gen expressions and list comps:

py> i = "spam"
py> x = [i+1 for i in range(10)]
py> i
'spam'


> It's a knotty problem. I'm currently inclined to the inner scope idea
> (like a comprehension), but that's inconsistent with the statement
> form of try/except. Is that difference going to confuse people?

I didn't think so. I didn't even realise that exceptions unbind the "as" 
name, instead of using a separate scope. I don't expect anyone is 
*relying* on that unbind-the-name behaviour, but even if they are, 
they can just keep using the try...except statement form.


> Alternatively, what would it be like if an expression could do a name
> binding and unbinding (consistently with the statement form)? Would
> that confuse people no end?

It would confuse, surprise and annoy me. I presume there are good 
reasons why the try...except statement does an unbind instead of using a 
new scope, but I really don't want to repeat that behaviour.


-- 
Steven


More information about the Python-ideas mailing list