Skip to content

Why doesn't flake8 mark this as an unused import?

Anthony Sottile edited this page Nov 2, 2016 · 1 revision

Consider the following case:

import a
import a.b  # technically unused!

print(a.x)

pyflakes (the library that flake8 uses for some of the linting detection) is very timid about doing import analysis. When considering imports, import a and import a.b.c.d only introduce the a symbol into the global scope. Since a is used on line 4, both of those imports are considered "used".

One may think, this is absurd! Surely it could know that the second import is unnecessary because of the first!

Consider this case:

import a
import a.b

print(a.z.x)
# a/b.py
import a.z

Admittedly this is a bit of an evil case (and you should never ever do this!). In this case, though it is equivalent to the first case, the second import is necessary (to perform a side-effect of making the a.z module available).