jendrikseipp / vulture

Find dead Python code
MIT License
3.42k stars 150 forks source link

"unused import" false positives #192

Closed chris-rands closed 4 years ago

chris-rands commented 4 years ago

Thanks for the nice tool. I've encountered a few "unused import" false positives recently of 2 types. 1st case is where the import is merely tested, e.g.:

try:
    import a
except ImportError:
    print("a not available")

2nd case is in __init__.py files, where it is common to import modules that are not directly used in the file

jendrikseipp commented 4 years ago

I agree that we should fix these two cases. Would you like to write a pull request for either of the two cases?

RJ722 commented 4 years ago

Let's fix the first case here. I'd raise a PR.

jendrikseipp commented 4 years ago

Thinking about the first case again, I'm not sure whether we should do anything about it. In the example above, a should be reported as unused, I think. Or am I missing something? Do you see an example with a real false-positive unused import?

chris-rands commented 4 years ago

sorry i've not had time to help with any PR, but to clarify the first example:

$ cat a.py 
var = True
$ cat b.py 
try:
    import a
    from a import var
    print(var)
except ImportError:
    print("a not available")
$ python b.py 
True
$ vulture b.py 
b.py:2: unused import 'a' (90% confidence)
jendrikseipp commented 4 years ago

Thanks for the example! However, a is still unused, since you import var directly as well.

chris-rands commented 4 years ago

true, the actual context i found this is in unit tests where we raise a custom exception/handling when the import is not found. in this case importing a is useful without using the import, i guess probably better to white list it though

jendrikseipp commented 4 years ago

I agree. If you find an example where we should adapt Vulture, feel free to post it here.

chris-rands commented 4 years ago

here's a couple of real examples for clarity

https://github.com/biopython/biopython/blob/master/Tests/test_codonalign.py#L233-L254

https://github.com/biopython/biopython/blob/master/Tests/test_GenomeDiagram.py#L16-#L24

jendrikseipp commented 4 years ago

I think in the first example, you could simply just do from scipy.linalg import expm instead of import scipy and in the second example, you could remove the imports that are unused.