How to ignore Pyflakes errors ‘imported but unused’ in ‘__init__.py’ files?

Question:

I split my tests across multiple Python files:

tests
├── __init__.py
├── test_apples.py
└── test_bananas.py.py

I import the tests in the ‘__init__.py’ file:

from test_apples import ApplesTest
from test_bananas import BananasTest

However running Pyflakes on the command-line:

pyflakes .

outputs the following errors:

tests/__init__.py:1: [E] PYFLAKES:'ApplesTest' imported but unused
tests/__init__.py:2: [E] PYFLAKES:'BananasTest' imported but unused
Asked By: Venkatesh Bachu

||

Answers:

Add # pyflakes.ignore comment on every line you want to ignore (in your case import statements).

Answered By: ILYA Khlopotov

In my version of PyFlakes (0.7.3), using __all__ works.

Additionally, to skip a line, you should add # noqa.

Answered By: dustinfarris

Sometimes you have to skip a line.
According to the current versions docs (flake8 2.4.1)
The files that contain

# flake8: noqa

are skipped. This works, and # noga, # pyflakes.ignore not.

Answered By: horbor

To ignore all errors F401 (‘imported but unused’) in ‘__init__.py’ files, the option ‘per-file-ignores’ which has been available since version 3.7.0 of Flake8 (a better Pyflakes) is very convenient. It can be used on the command-line:

flake8 --per-file-ignores="__init__.py:F401" .

or in a configuration file (‘.flake8’, ‘setup.cfg’ or ‘tox.ini’):

[flake8]
per-file-ignores = __init__.py:F401
Answered By: Maggyero

The imports are interpreted as being unused because your linting tool doesn’t understand how it’s being used.

The most comprehensive fix is to ensure that these names are clearly exported from your module. Either by setting __all__, which is a mechanism for exhaustively enumerating the exported names, or by giving the imports explicit exported names using as.

from test_apples import ApplesTest as ApplesTest

However, I would generally recommend using a test runner that scans for test cases rather than importing them all, as that gives you more confidence that you’re definitely running all of your tests.

Answered By: Andrew Aylett

add # noqa: F401 to the end of your line (F401 is a code of this error)

Example:
from django.utils import http # noqa: F401

Answered By: Sinisa Rudan
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.