Call Python script from pylint init-hook
This note is deprecated as of December 2024. I recommend using source-roots
instead, which is available from Pylint v2.17.7. See this note.
The .pylintrc
has a init-hook
field, which is a one-liner of Python code that gets executed when pylint initialises. While you can use semicolons to write multiple lines within the init-hook
, this does not scale well, and does not diff well. There seems to be no way to do multi-line Python code within the init-hook
, so the best way I’ve found is to use the init-hook
to import a separate file, in which you can write multi-line Python code.
First, create an import_hook.py
in the same directory as your .pylintrc
. Put in here whatever Python code you would like. Typically this might be adding stuff to the sys.path
:
import sys
sys.path.append("foo")
sys.path.append("bar")
# etc...
Then update the .pylintc
to import the import_hook.py
. We’re being lazy here and making use of import side-effects (i.e. there is no if __name__ == "__main__"
in the import_hook.py
, all code just executes upon import). That could easily be avoided but it would make the init-hook
a little longer:
init-hook="import imp, os; from pylint.config import find_pylintrc; imp.load_source('import_hook', os.path.join(os.path.dirname(find_pylintrc()), 'import_hook.py'))"