Comment 3 for bug 1408774

Revision history for this message
Phil Frost (bitglue) wrote :

Pyflakes doesn't do that for simple variables. There's a test for what you propose:

https://github.com/pyflakes/pyflakes/blob/1c9a81913bf29977489eb132e9f0103f6b07f62c/pyflakes/test/test_other.py#L343

It's skipped with the comment "Too hard to make this warn but other cases stay silent". I tried digging through the history to find where that's introduced. It's here:

https://github.com/pyflakes/pyflakes/commit/3ef443aab87c436868746e7e855fb360eda8eaf8#diff-d18f55ece21d21fb172322f7db700d6aR164

Which, I think, is just an import from prehistory. So, it's a little hard to get the exact context that led to that decision, but it's been that way for a long time.

The reason, I suspect, is that this is pretty common:

foo = 'something'
if condition:
  foo = 'something else'

Now the problem becomes that pyflakes can't understand if "condition" is true or not. Currently, pyflakes just processes all conditional paths as if they were all taken. That means if you use a variable only sometimes, python counts it as used. So the code above, to pyflakes, might as well be:

foo = 'something'
foo = 'something else'

The example you pose, with "for foo in maybe_empty_list", is just another flavor of that, and while it isn't a common case, it is a case sometimes, and a valid one, and pyflakes assumes you know better, and if you really care about the correctness of your code you will write a unit test.

Sometimes people propose fancier logic than just taking all paths, but I think if you go down this road, you either end up with incomplete logic that's wrong sometimes, or you become a python interpreter. I'm certainly open to ideas though.