Support for PEP 484 style # type comments
I'd like to open a discussion about whether flake8 and pyflakes should include support for # type:
comments as standardized by PEP 484. The way PEP 484 is currently written, names used in such type comments must be imported using regular import statements. When such an imported name is used exclusively in a # type
comment it may elicit a spurious warning about an unused import ("F401 UnusedImport"). While it's easy to shut this up by putting # noqa
on the import line, that gets ugly quick. (That's the solution we have adopted so far at Dropbox, but we really need something better.)
While you might think that it would be enough to suppress F401 about from typing import ...
it is also common to have to import some other class that is not instantiated directly in the code but still needs to be named in a # type
comment. This is especially prevalent in Python 2 code where signature annotations are used; this is a recent addition to PEP 484: https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code.
I've developed a hack to deal with this, but it is pretty darn ugly. The problem is that the UnusedImport warning (and similar warnings like UndefinedName and UnusedVariable) are implemented by pyflakes, which takes an AST. Comments are not represented in the AST. So my hack is to append extra lines to the end of the file containing expressions that are copied (almost) literally from the # type
comments -- but this is really hideous. A more principled implementation might be to switch to the parser implemented in lib2to3, which does represent comments; but that could be a big effort, plus it's slower.
Finally -- I couldn't find a tracker for pyflakes, otherwise I would have reported this there. I actually developed the hack twice -- once for pyflakes (as a diff to pyflakes/api.py) and then again for flake8 (as a monkeypatch for pep8.Checker.check_ast).
Thoughts?