Pylint Plugin Utilities
Pylint Plugin Utilities (version 0.9.0) provides a collection of helper functions and classes designed to simplify the development of custom Pylint checkers and transformers. It abstracts away common boilerplate and provides tools for AST manipulation and message suppression. The library maintains a steady release cadence, typically aligning with Pylint's own major versions to ensure compatibility.
Warnings
- breaking Pylint version compatibility changed; `pylint-plugin-utils` 0.9.0 now requires `Pylint >= 2.16`.
- breaking The `register_linter_extension` function has been removed.
- breaking The `fix_pythonpath` function has been removed.
- gotcha Pylint plugins are not automatically discovered by default; they must be explicitly loaded.
Install
-
pip install pylint-plugin-utils
Imports
- suppress_message
from pylint_plugin_utils.utils import suppress_message
- add_message
from pylint_plugin_utils.messages import add_message
- AstBuilder
from pylint_plugin_utils.ast_builder import AstBuilder
Quickstart
# my_plugin.py
from pylint.checkers import BaseChecker
from pylint_plugin_utils.messages import add_message
from pylint_plugin_utils.utils import suppress_message
# Define a custom message ID and details
MY_MSG = 'W9999'
MY_MSG_ID = 'no-direct-print'
MY_MSG_STR = 'Avoid calling "print" directly in production code.'
class NoPrintChecker(BaseChecker):
"""
Checks for direct calls to the 'print' function.
"""
name = 'no-print-checker'
priority = -1
msgs = {
MY_MSG: (
MY_MSG_STR,
MY_MSG_ID,
'Avoid using print for logging in production; use a proper logger instead.',
)
}
def visit_call(self, node):
"""Called for every function call."""
if node.func.as_string() == 'print':
add_message(self, MY_MSG_ID, node=node)
# Example of using suppress_message decorator
@suppress_message('invalid-name')
def ThisFunctionIsAllowedToHaveAnInvalidName():
pass
def register(linter):
"""Register the checker with Pylint."""
linter.register_checker(NoPrintChecker(linter))
# To run this plugin:
# 1. Save the above code as `my_plugin.py`.
# 2. Create a test file, e.g., `test_code.py`:
# print("Hello, World!")
# ThisFunctionIsAllowedToHaveAnInvalidName()
# 3. Run Pylint with the plugin: `pylint --load-plugins=my_plugin test_code.py`
# This will report 'no-direct-print' for `print` and suppress 'invalid-name' for the function.