pythonpylinttoxpyproject.toml

Pylint tests directory with src layout raises import-error


I'm using the following src layout:

src
├── packagename
│   ├── __init__.py
│   └── subpackage
│       └── __init__.py
│       └── somemodule.py
├── .pylintrc 
│   ...
tests
├── subpackage
│   └── __init__.py 
│   └── test_somemodule.py
├── __init__.py
├── .pylintrc
│   ...
pyproject.toml

We perform linting of tests directory, with some relaxed rules defined at tests/.pylintrc. We had no problem with this when using a non-src layout. pytest is working properly thanks to the following directive at pyproject.toml, albeit might had also been solved by installing the package with tox:

[tool.pytest.ini_options]
pythonpath = [
  "src"
]

When running lint as:

pylint --rcfile src/packagename/.pylintrc -j 0 src
pylint --rcfile tests/.pylintrc j 0 tests

we are getting errors such as E0401: Unable to import 'packagename.subpackage' (import-error).

How could this be fixed?


Solution

  • One option is to modify the Python path in an init-hook in your .pylintrc, e.g.

    [MASTER]
    init-hook=
        import sys
        sys.path.append("./src")