asottile / pyupgrade

A tool (and pre-commit hook) to automatically upgrade syntax for newer versions of the language.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Automatically remove try-except blocks.

EwoutH opened this issue · comments

When currently applying pycharm on a Python 2.7-compatible codebase, a few of such cases pop up:

try:
    from collections.abc import Iterable
except ImportError:
-    from collections import Iterable
+    from collections.abc import Iterable

It would be useful if pyupgrade could detect if the code in both the try and except end up identical, and if so, remove the block.

In that case, the diff should become:

-try:
-    from collections.abc import Iterable
-except ImportError:
-    from collections import Iterable
+from collections.abc import Iterable

the correct way to write such a concept is with if sys.version_info < (...): which would be auto-rewritten. the try except pattern is error-prone

while this is fixable -- it's a bit of a garbage-in-garbage-out situation

Fully agreed it’s not a good pattern. Would still be nice to be able to fix it automatically though!