Python 3 removes name binding from outer scope

Ethan Furman ethan at stoneleaf.us
Mon Jul 24 22:35:53 EDT 2017


On 07/24/2017 06:41 PM, Ben Finney wrote:

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


Something like:

     try:
         ....
     except ZeroDivisionError as dead_exc:
         exc = dead_exc
         ....
     ....
     print(text_template.format(exc=exc)

> Why is the ‘exc’ binding deleted from the outer scope?

Help prevent memory leaks and  allow resources to be cleaned up sooner.

> How are we meant
> to reliably preserve the name binding to use it *after* the ‘except’
> clause?

Reassign to something else, like my example above.

> When did this change come into Python, where is it documented?

Documented at:  https://docs.python.org/3/reference/compound_stmts.html#the-try-statement [1]

Don't recall exactly when changed.

> Would I be right to report this as a bug in Python 3?

No.

--
~Ethan~


[1] Thanks to https://stackoverflow.com/q/29268892/208880



More information about the Python-list mailing list