How do I make a global pylint installation use a local Python interpreter to prevent "Unable to import" errors?

923 Views Asked by At

I've installed pylint using pipx so that it is available across all my virtual environments without having to add pylint as a dev dependency for each project. I'm also using VS Code and have the following settings to enable pylint and point towards the global pylint that I've installed with pipx in the .local/ directory.

{
    "python.linting.enabled": true,
    "python.linting.pylintEnabled": true,
    "python.linting.pylintPath": "~/.local/bin/pylint",
}

The issue I have is that pylint import errors are displaying for packages I have installed within the virtual environment, and so I don't know how to link this global pylint with the local virtual environment in my project so it can recognise the packages. In VS Code I have the Python interpreter within the virtual environment selected.

I'm guessing that I need to provide some setting to change the Python Path that pylint uses to point to the currently active interpreter within VS Code. I'm just not sure whether that setting exists, nor of any workaround. Of course I could just install pylint as a development dependency inside my project, but I'd rather just make use of the global pylint if possible. Does anyone know of a solution?

2

There are 2 best solutions below

0
On

I tried with pylint-venv, and it works. First, we can install pylint-venv in the global level (outside the virtual env):

pip install pylint-venv

Then inside the pyproject.toml file for this project, we can configure a init-hook for pylint:

[tool.pylint.main]
init-hook ="""
try:
  import pylint_venv
except ImportError:
  pass
else:
  pylint_venv.inithook()
"""
0
On

I've been playing around recently with the exact same setup and experienced the same issue. I followed the hints I had found in some other answers (like this one), which was to use Pylint's init-hook option. So now I have a global .pylintrc file in my home folder (i.e. parent folder of all project folders) which contains the following line:

[MASTER]
ignore=.venv
init-hook="import sys; from pathlib import Path; sys.path.append(str(next(Path.cwd().glob('.venv/lib/*/site-packages'))))"

Naturally, for this to work, the working directory has to be the project's root folder - in VS Code this is most likely the 'workspace directory'. Also, a consistent approach for projects' virtual environments is required, i.e. that the venv resides in the project's .venv folder or that there is a .venv symlink to the venv's root folder. And also take care that no other Pylint config file takes precedence over the fallback 'global' one, otherwise you'll have to modify that one as well.

In addition, I've just stumbled across a seemingly very pertinent project called pylint-venv. I haven't had the chance to tinker around with it yet, but you might want to check that out as well.