pyflakes icon indicating copy to clipboard operation
pyflakes copied to clipboard

Overriding imports gives incorrect error

Open Wilfred opened this issue 13 years ago • 5 comments

The following code:

try:
    import cPickle as pickle
except ImportError:
    import pickle

def foo():
    return pickle.dumps

Gives the following error: foo.py:4: redefinition of unused 'pickle' from line 2. However, it is actually used.

Expected error would be "'pickle' imported but unused" or perhaps something like "redefinition of 'pickle' from line 2"

Wilfred avatar Aug 08 '11 18:08 Wilfred

I understand why this is misleading, but at the time of parsing line 4, pickle is unused.

The primary error is for the redefinition, and really unrelated to weather or not pickle is unused.

jehiah avatar Sep 06 '11 03:09 jehiah

I don't quite follow your logic, sorry. Consider this code:

import math

def log(x): return math.log(x)

At time of parsing line 1, math is unused. But usage should be considered after parsing the whole file, and in this example it is.

(I certainly agree that "'pickle' imported but unused" is not an improvement, and it should be "redefinition of 'pickle' from line 2")

Wilfred avatar Sep 06 '11 13:09 Wilfred

I can understand why the error would come up, but this is a really common pattern. Isn't there any way you can recognize it and ignore it?

Daenyth avatar Mar 06 '12 16:03 Daenyth

Hm, pylint sensibly accepts something like:

if some_cond:
    a = 2
else:
    a = 3
print a

Perhaps the same logic could be extended to the try/except, since given:

try:
    something_that_might_raise_an_exception()
    a = 2
except:
    a = 3
print a

a=3 doesn't necessarily redefine a. It's a less well defined situation than the if/else, but as Daenyth says, this is a common pattern, and it'd be nice if it didn't cause the warning!

dbr avatar Mar 12 '12 11:03 dbr

This is really duplicate of issue #13 and is fixed with pull request #28.

saper avatar Jan 06 '13 14:01 saper