Python 3 removes name binding from outer scope

Steve D'Aprano steve+python at pearwood.info
Mon Jul 24 22:52:17 EDT 2017


On Tue, 25 Jul 2017 11:41 am, Ben Finney wrote:

> Howdy all,
> 
> How can I stop Python from deleting a name binding, when that name is
> used for binding the exception that is caught? When did this change in
> behaviour come into Python?
> 
> 
> I am writing code to run on both Python 2 and Python 3::
> 
>     exc = None
>     try:
>         1/0
>         text_template = "All fine!"
>     except ZeroDivisionError as exc:
>         text_template = "Got exception: {exc.__class__.__name__}"
> 
>     print(text_template.format(exc=exc))
> 
> Notice that `exc` is explicitly bound before the exception handling, so
> Python knows it is a name in the outer scope.

Ethan has already answered your direct question, but I'd like to make an
observation: there's no "outer scope" here, as the try...except statement
doesn't introduce a new scope. All your code above runs in a single scope with
a single namespace. It isn't that the except block is in a different scope, but
that the except statement now explicitly calls "del" on the exception name when
the block ends.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list