[Python-ideas] A proliferation of (un-)Pythonically programmatic pragmas

Ned Batchelder ned at nedbatchelder.com
Mon Nov 13 19:50:25 EST 2017

On 11/13/17 2:10 PM, Barry Warsaw wrote:
> I love many of the ancillary tools that help improve the quality of my
> Python code, including flake8, coverage, and mypy.  Each of these
> usually produces some great diagnostics, but none of them are perfect,
> so they also produce false positives that have to be suppressed.
> Each of these tools supports "pragmas", i.e. comments you can add to a
> line of code to suppress a warning.  E.g. with flake8 I can say:
>      import readline, rlcompleter        # noqa: F401
> to suppress the flake8 warnings about unused imports.  These modules
> work by side-effect, which of course a static analyzer can't know.
> Similarly, when mypy complains about a line it's confused on, I can add
> a comment to suppress the useless warning:
> try:
>      from pathlib import Path, PurePath
> except ImportError:
>      from pathlib2 import Path, PurePath      # type: ignore
> And when I want to boost coverage, but I know that some lines aren't
> covered under some versions of Python, I can do something like:
>              self.send_error(HTTPStatus.NOT_FOUND)   # pragma: nocover
> These are all well and good until I have to *combine* suppressions.
> E.g. in the pathlib2 pragma to mypy, I also get a flake8 warning and
> I've tried just about every combination of pragma comment I can think
> of, but I've not been able to make both tools happy.  I've resorted to
> refactoring the code into an entire module for flake8 to ignore and added:
>      # flake8: noqa
> to suppress all warnings in the file.  I actually have hit on a few
> places where I need to suppress warnings from all three tools on the
> same line, and I basically can't do it.
> The specifics aren't as important as the general use case: multiple
> tools competing for the same valuable real-estate.
> I have no ideas how to improve the situation, and of course any solution
> would involve some coordination between all of these tools, but it's
> beginning to feel like a losing battle.  Is there a better way?

Coverage.py has no fixed syntax for its pragmas.  The default is "# 
pragma: no cover", but you can configure any regex you like, and it's 
matched against the entire line, not just the comment.  This makes it 
possible to exclude lines based on the source, or to change the syntax 
of the pragma.

If a PEP is written with a common syntax, I can add it to coverage.py's 


More information about the Python-ideas mailing list