Wed 24 Jan 2007
Lately, I’ve been working on a PEP to change how Python 3’s “except” statements work. The highlights:
(Anyone wanting to discuss these should join the python-3000 list and comment there.)
-
The grammar for “except” statements will change from
except_clause: 'except' [test [',' test]]
in Python 2 to
except_clause: 'except' [test ['as' NAME]]
in Python 3. This is being done to eliminate a syntactic ambiguity where the parser can’t tell whether
except EXPRESSION, EXPRESSION:
should be interpreted as
except TYPE, TYPE:
or
except TYPE, TARGET:
Python 2 opts for the latter semantic, at the cost of requiring the former to be parenthesized.
Converting Python 2-style “except” statements to Python 3 can be handled automatically (for the most part) by Guido van Rossum’s 2to3 utility.
-
As specified in PEP 352, the ability to treat exceptions as tuples will be removed, meaning this code will no longer work:
except os.error, (errno, errstr):
Because the automatic unpacking will no longer be possible by default, the ability to use tuples as “except” targets at all will be removed.
-
PEP 344 specifies that exception instances in Python 3 will possess a
__traceback__attribute. The Open Issues section of that PEP includes a paragraph on garbage collection difficulties caused by this attribute, namely a “exception -> traceback -> stack frame -> exception” reference cycle, whereby all locals are kept in scope until the next GC run. Python 3 will resolve this issue by making sure the target name is deleted at the end of the “except” suite, thus breaking the cycle.This will be done by having the compiler emit appropriate bytecode to translate
try: try_body except E as N: except_body ...to this (in Python 2.5 terms):
try: try_body except E, N: try: except_body finally: N = None del N ...An implementation of this has already been checked into the p3yk [sic] branch.
January 24th, 2007 at 23:18
Thanks for this article, informative and to the point. I wish more of the articles on Planet Python were the same.