unimport icon indicating copy to clipboard operation
unimport copied to clipboard

False positive on `sys.version_info`-dispatched imports for mypy

Open sirosen opened this issue 1 year ago • 2 comments

First, thanks for an awesome project! I'm working on a sizeable refactor, and wanted a modernized version of autoflake8. A quick run of unimport -r src/**/*.py saved me a lot of time. ❤️ There was only one false positive, below.


mypy recommends checking sys.version_info in order to do imports which dispatch between typing and typing_extensions. I've found that some import structures (read: handling ImportError) are not well understood by mypy for this purpose, so it's generally a good idea to follow their guidance if you want type checking to behave well in all environments.

MWE

Here's a reproducer:

# repro.py
import sys

if sys.version_info >= (3, 8):
    from typing import Literal
else:
    from typing_extensions import Literal


def foo(x: Literal["a", "b"]) -> int:
    return ord(x)

Expected Result

unimport -d repro.py should show no diff.

Actual Result

unimport -d repro.py shows

--- repro.py

+++

@@ -2,7 +2,7 @@

 import sys

 if sys.version_info >= (3, 8):
-    from typing import Literal
+    pass
 else:
     from typing_extensions import Literal

sirosen avatar Jul 13 '22 02:07 sirosen

There is currently no if statement analysis, to solve this issue, we need to apply an analysis similar to the analysis we used for ImportError.

Thank you for the Issue and your comments, I will work on it.

hakancelikdev avatar Jul 15 '22 16:07 hakancelikdev

For now If you want you can skip this issue using skip feature, check out -> https://unimport.hakancelik.dev/#skip-import

hakancelikdev avatar Jul 15 '22 17:07 hakancelikdev