Search code examples
pythontoxflake8

Applying alternate flake8 rules to a subset of files


I have a project where I'm using tox for testing, which runs flake8 tests. I'd like to apply a different flake8 configuration to my tests directory from everything else; I'd like to ignore E402 on my tests because I'm messing with sys.path before importing the module to be tested.

The flake8 config syntax only lets you apply one configuration to files matched by include/exclude, so I've added ./tests/.flake8 to add a configuration that applies only to those files.

./tox.ini

[tox]
envlist = lint, py27, py36

[testenv]
commands =
    coverage run --source=myModule -a setup.py test

[testenv:lint]
basepython = python3
ignore_errors = True
deps =
    -r{toxinidir}/requirements_test.txt
commands =
    flake8
    pylint myModule
    pydocstyle myModule tests

[flake8]
count = true
statistics = True

./tests/.flake8

[flake8]
ignore = E402

With the flake8 options in my tox.ini file, the dotfile is ignored always. With no options in the tox.ini file the dotfile is used by flake8 run from the command line, but ignored when it's run by tox.

It looks like there is no way to apply a different flake8 configuration to different sets of files under the same project. Have I missed something in the configuration syntax that would allow me to do what I want here?


Solution

  • As of version 3.7.0 flake8 now includes a flag to do what you want: per-file-ignores. To use it in your configuration file, do something like this:

    [flake8]
    per-file-ignores =
        tests/*: E402
    

    It can also be applied on the command line by adding a flag like this to your flake8 call:

    --per-file-ignores=tests/*.py:E402