guettli guettli - 1 year ago 43
Python Question

Automatic Code Update for Exception Handling in Python

This older syntax was removed in Python 3:

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


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

Wow, that's a lot

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

Answer Source

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