Sam Hooke

Call Python script from pylint init-hook

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_hook.py §
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:

.pylintrc §
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'))"

These are rough notes that vary greatly in quality and length, but prove useful to me, and hopefully to you too!

← Previous: Python DEPRECATION warning and pip --no-cache-dir breakage
Next: Python click: allow user to retry input upon validation failure →