[Python-ideas] except expression

Chris Angelico rosuav at gmail.com
Mon Feb 17 07:28:47 CET 2014


On Mon, Feb 17, 2014 at 4:29 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> 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.

Yeah, the unbinding is really weird. I didn't know about it until I
started experimenting, too... and then went digging in the docs and
found out that it implicitly creates a 'finally' that dels the name.

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

The inner scope does seem to demand a function call, though.

Maybe this is a good opportunity to introduce the concept of
"sub-scopes" for specific constructs. Comprehensions and 'as' clauses
(I doubt anyone will object to the statement try/except being brought
in line with this) could then use a sub-scope inside the existing
function; it'd affect only the LOAD_FAST opcode, I think - assignment
could delete it from the sub-scope and put it into the main scope.
This would mean that:

try:
    f()
except Exception as e:
    e = e
print(e)

would print out the exception. But that would be a completely separate
PEP. I'd like it to happen, but it's not part of exception
expressions.

ChrisA


More information about the Python-ideas mailing list