151

A lot of our modules start with:

try:
    import json
except ImportError:
    from django.utils import simplejson as json  # Python 2.4 fallback.

...and it's the only Pyflakes warning in the entire file:

foo/bar.py:14: redefinition of unused 'json' from line 12

How can I get Pyflakes to ignore this?

(Normally I'd go read the docs but the link is broken. If nobody has an answer, I'll just read the source.)

a paid nerd
  • 30,702
  • 30
  • 134
  • 179

9 Answers9

235

If you can use flake8 instead - which wraps pyflakes as well as the pep8 checker - a line ending with

# NOQA

(in which the space is significant - 2 spaces between the end of the code and the #, one between it and the NOQA text) will tell the checker to ignore any errors on that line.

MattDMo
  • 100,794
  • 21
  • 241
  • 231
yrstruly
  • 2,564
  • 1
  • 15
  • 3
  • If there only was a way to get this from some repo for EL6 :) - I guess I'll have to wrap this in a rpm myself. – Kimvais May 09 '12 at 04:54
  • @Kimvais, I'll probably be putting my ignorance on display here, but can you not get [setuptools](http://pypi.python.org/pypi/setuptools) or [distribute](http://pypi.python.org/pypi/distribute)? Either of these will give you the `easy_install` command. Then you can get [pip](http://pypi.python.org/pypi/pip/1.1), with which you can install flake8. At least on Ubuntu, `pip install` is how I acquire Python packages not provided in the distribution. – yrstruly May 10 '12 at 16:09
  • yes, I do use pip, but some people do not like software to be installed outside the package management system - luckily `python setup.py bdist_rpm` works on most packages. – Kimvais May 10 '12 at 16:43
  • 23
    nice, but not a solution for pyflakes – ezdazuzena Jul 31 '14 at 15:36
  • 8
    Tips: add this line `# flake8: noqa` will tell flake8 to ignore validation for the whole file. – Reorx Jul 25 '15 at 05:48
  • 3
    `# noqa` only ignores certain warnings/errors, but not all -- in order to deal with this, a workaround involves installing/using the package at https://pypi.python.org/pypi/flake8-respect-noqa – Mark Jan 18 '16 at 00:15
  • This may seem irrelevant, but is there any expansion for noqa? – Aswin Murugesh Mar 09 '16 at 08:17
  • I have to come back to this post every few months because I end up thinking it is `# NOQC`. – Bruno Bronosky Jul 14 '17 at 15:00
  • Works in **PyCharm**. – Bob Stein Oct 16 '17 at 20:20
  • 13
    Tips `# noqa: F841` means ignoring only `F841` error at the line. – SangminKim Feb 12 '18 at 16:00
  • Use `flake8 --select=F` to get flake8 to act like pyflakes. – Pyprohly Sep 13 '20 at 18:06
56

I know this was questioned some time ago and is already answered.

But I wanted to add what I usually use:

try:
    import json
    assert json  # silence pyflakes
except ImportError:
    from django.utils import simplejson as json  # Python 2.4 fallback.
mfussenegger
  • 3,931
  • 23
  • 18
9

Yep, unfortunately dimod.org is down together with all goodies.

Looking at the pyflakes code, it seems to me that pyflakes is designed so that it will be easy to use it as an "embedded fast checker".

For implementing ignore functionality you will need to write your own that calls the pyflakes checker.

Here you can find an idea: http://djangosnippets.org/snippets/1762/

Note that the above snippet only for for comments places on the same line. For ignoring a whole block you might want to add 'pyflakes:ignore' in the block docstring and filter based on node.doc.

Good luck!


I am using pocket-lint for all kind of static code analysis. Here are the changes made in pocket-lint for ignoring pyflakes: https://code.launchpad.net/~adiroiban/pocket-lint/907742/+merge/102882

Adi Roiban
  • 1,293
  • 2
  • 13
  • 28
  • 1
    divmod.org is down, but the goodies can be found at launchpad (https://code.launchpad.net/divmod.org). – thebjorn May 05 '12 at 13:44
7

To quote from the github issue ticket:

While the fix is still coming, this is how it can be worked around, if you're wondering:

try:
    from unittest.runner import _WritelnDecorator
    _WritelnDecorator; # workaround for pyflakes issue #13
except ImportError:
    from unittest import _WritelnDecorator

Substitude _unittest and _WritelnDecorator with the entities (modules, functions, classes) you need

-- deemoowoor

endolith
  • 25,479
  • 34
  • 128
  • 192
Daenyth
  • 35,856
  • 13
  • 85
  • 124
  • and `_WritelnDecorator;` does absolutely nothing, right? So I can use this to get pyflakes to ignore unused variables that are actually used inside [eval](http://docs.python.org/2/library/functions.html#eval) or [numexpr](https://code.google.com/p/numexpr/) strings by listing the variables on a separate line? Is the semicolon even necessary? – endolith May 23 '13 at 18:50
  • 2
    Actually, using `dis.dis`, this apparently does a `LOAD_FAST` and `POP_TOP` for each variable on a line by itself (puts it on the stack and then removes it from the stack?), so it's not doing nothing. Better than `assert`, though. – endolith May 23 '13 at 19:10
  • 1
    Semi-colon not necessary. Asserts can be ignored thru the optimize switch so not totally useless. – Gringo Suave Oct 28 '19 at 19:50
6

Here is a monkey patch for pyflakes that adds a # bypass_pyflakes comment option.

bypass_pyflakes.py

#!/usr/bin/env python

from pyflakes.scripts import pyflakes
from pyflakes.checker import Checker


def report_with_bypass(self, messageClass, *args, **kwargs):
    text_lineno = args[0] - 1
    with open(self.filename, 'r') as code:
        if code.readlines()[text_lineno].find('bypass_pyflakes') >= 0:
            return
    self.messages.append(messageClass(self.filename, *args, **kwargs))

# monkey patch checker to support bypass
Checker.report = report_with_bypass

pyflakes.main()

If you save this as bypass_pyflakes.py, then you can invoke it as python bypass_pyflakes.py myfile.py.

http://chase-seibert.github.com/blog/2013/01/11/bypass_pyflakes.html

johntellsall
  • 14,394
  • 4
  • 46
  • 40
Chase Seibert
  • 15,703
  • 8
  • 51
  • 58
  • I am not sure what changed or if there was an error in the original code but my version of pyflakes (0.9.2) requires that `text_lineno = args[0] - 1` be changed to `text_lineno = args[0].lineno - 1`. I recommend updating this answer to reflect this. – John Lunzer Jun 14 '18 at 13:03
5

Flake gives you some options to ignore violations.

My favorite one is to make it explicit and ignore the specific violation inline:

my invalid code # noqa: WS03

And you have the others already cited options.

  1. Ignore all validations in the line:
my invalid code # NOQA
  1. Ignore all validations in the file. Put in its first line:
# flake8: noqa: E121, E131, E241, F403, F405

Or configure to ignore it as a parameter in you flake8 configuration.

neves
  • 33,186
  • 27
  • 159
  • 192
1

You can also import with __import__. It's not pythonic, but pyflakes does not warn you anymore. See documentation for __import__ .

try:
    import json
except ImportError:
    __import__('django.utils', globals(), locals(), ['json'], -1)
jrennie
  • 1,937
  • 12
  • 16
mrijken
  • 128
  • 5
0

I created a little shell script with some awk magic to help me. With this all lines with import typing, from typing import or #$ (latter is a special comment I am using here) are excluded ($1 is the file name of the Python script):

result=$(pyflakes -- "$1" 2>&1)

# check whether there is any output
if [ "$result" ]; then

    # lines to exclude
    excl=$(awk 'BEGIN { ORS="" } /(#\$)|(import +typing)|(from +typing +import )/ { print sep NR; sep="|" }' "$1")

    # exclude lines if there are any (otherwise we get invalid regex)
    [ "$excl" ] &&
        result=$(awk "! /^[^:]+:(${excl}):/" <<< "$result")

fi

# now echo "$result" or such ...

Basically it notes the line numbers and dynamically creates a regex out it.

phk
  • 2,002
  • 1
  • 29
  • 54
0

For flake8, which is recommended alternative (compare flake8 vs pyflakes here)

Add the first line like:

# flake8: noqa: E121, E131, E241, F403, F405

in general:

# flake8: noqa: <code>[, <code> ...]

This way in one line you can silent the entire file and do it for many ignore statements at once, which is often a case.

Sławomir Lenart
  • 7,543
  • 4
  • 45
  • 61