flake8-plugin-utils
flake8-plugin-utils is a Python package providing base classes and utility functions to simplify the creation of custom plugins for the Flake8 linter. It aims to reduce boilerplate and offer helpful tools for AST (Abstract Syntax Tree) analysis within Flake8 plugins. The current version is 1.3.3, released on 2022-01-14, with a moderate release cadence based on contributions.
Warnings
- breaking When using `flake8-plugin-utils` with typing (e.g., MyPy), the `Plugin` and `Visitor` classes are generic. If your plugin does not have any custom configuration, you must explicitly inherit from `Plugin[None]` and `Visitor[None]` to avoid type-checking errors.
- gotcha Flake8 plugins are registered via `setuptools` entry points. Incorrectly configuring the `entry_points` in your `setup.py` or `pyproject.toml` can lead to your plugin not being detected or conflicting with other plugins. Ensure your entry point is unique and correctly points to your plugin class.
- gotcha When developing and testing Flake8 plugins, ensure you understand how Flake8 handles configuration files and local plugins. Issues can arise if configuration sections for uninstalled plugins are left in `.flake8`, `setup.cfg`, or `pyproject.toml`.
Install
-
pip install flake8-plugin-utils
Imports
- Error
from flake8_plugin_utils import Error
- Visitor
from flake8_plugin_utils import Visitor
- Plugin
from flake8_plugin_utils import Plugin
- assert_error
from flake8_plugin_utils import assert_error
- assert_not_error
from flake8_plugin_utils import assert_not_error
Quickstart
from flake8_plugin_utils import Error, Visitor, Plugin, assert_error
import ast
# Define a custom error
class MyError(Error):
code = 'X100'
message = 'Avoid using the name {thing}'
# Define a custom visitor
class MyVisitor(Visitor):
def visit_Name(self, node: ast.Name):
if node.id == 'footgun':
self.report(node, thing=node.id)
# Define the plugin (without configuration for simplicity)
class MyPlugin(Plugin[None]):
name = 'flake8-myplugin'
version = '0.1.0'
visitors = [MyVisitor]
# Example of testing the plugin (typically in a test suite)
def test_my_plugin_error():
src = """import os\nfootgun = 1"""
assert_error(MyVisitor, src, MyError, row=2, col=0, thing='footgun')
# To run the linter (outside this snippet, typically from command line)
# flake8 --isolated --select=X100 my_code.py
# or integrate via entry points in setup.py