guettli guettli - 3 months ago 9
Python Question

Automatic Code Update for Exception Handling in Python

This older syntax was removed in Python 3:

try:
...
except MyException, exc: # Don't do that!
...


New

try:
...
except MyException as exc:
...


I checked how many times the old syntax gets used in the code I work on:

find */* -name '*.py'|xargs grep 'except.*,.*:'| wc -l
551


Wow, that's a lot

Is there a way to automated this particular Python2 to Python3 update?

Answer

... answering my own question. I found the futurize from python-future:

futurize --write --nobackups --fix lib2to3.fixes.fix_except src/mylib/

It supports a lot of other fixes, but today I want to focus in the exception handling.

It works well and saves me a lot of time :-)