Pylint
Pylint is a widely used static code analyzer for Python. It inspects source code without execution to detect programming errors, enforce coding standards (like PEP 8), identify code smells, and suggest refactorings. It provides a detailed report and a code quality score. Pylint maintains an active development status with regular releases, including minor versions for new checks and bug fixes, and major versions that may introduce breaking changes to options or output formats.
Warnings
- breaking Pylint 4.x removes direct access to package metadata via `pylint.__pkginfo__`. Users should migrate to `importlib.metadata` for retrieving package information.
- breaking Pylint 4.x officially drops support for *launching* Pylint with Python 3.9. While it can still *lint* code written for Python 3.9 (or older) using `--py-version=3.9`, the environment running Pylint itself must be Python 3.10.0 or newer.
- breaking In Pylint 3.x, the behavior of enabling or disabling individual messages changed. The order of `--enable` or `--disable` flags (or their counterparts in configuration files) now strictly dictates their application, meaning later options can override earlier ones.
- gotcha Pylint's default configuration can be very verbose, especially on legacy or less-PEP 8 compliant projects. This often leads to an overwhelming number of messages upon first run.
- gotcha The `invalid-name` message often triggers due to Pylint's default expectation of `UPPERCASE` for module-level constants, which might conflict with project-specific naming conventions.
- gotcha Pylint relies on Python's module resolution mechanism. Incorrect `PYTHONPATH` settings or running Pylint from an unexpected working directory can lead to it analyzing the wrong module version or failing to import modules, resulting in `import-error` messages.
Install
-
pip install pylint -
pip install pylint[spelling]
Imports
- Run
from pylint.lint import Run
- TextReporter
from pylint.reporters.text import TextReporter
Quickstart
import os
import io
from pylint.lint import Run
from pylint.reporters.text import TextReporter
# Create a dummy Python file for linting
with open('my_module.py', 'w') as f:
f.write('"""A simple module."""
MY_CONSTANT = 10
def my_function(arg1, arg2): # arg2 is unused
return arg1 + MY_CONSTANT
')
# --- Command Line Usage ---
print("\n--- Command Line Pylint ---")
os.system('pylint my_module.py')
# --- Programmatic Usage ---
print("\n--- Programmatic Pylint ---")
# Capture output to a string buffer
pylint_output = io.StringIO()
reporter = TextReporter(pylint_output)
# Run Pylint on the module, disabling reports for cleaner output
# do_exit=False prevents sys.exit() on linting issues
Run(['my_module.py', '--disable=C0114,C0116,R0903', '--reports=no'], reporter=reporter, do_exit=False)
print(pylint_output.getvalue())
# Clean up the dummy file
os.remove('my_module.py')