Flake8 and pylama plugin that checks the ordering of import statements.
—
Flake8 and pylama linter integrations that provide command-line options, configuration parsing, and error formatting for seamless integration with Python linting workflows.
Flake8 plugin implementation that integrates import order checking into the flake8 linting framework.
class Linter(ImportOrderChecker):
"""Flake8 linter integration for import order checking."""
name = "import-order" # Plugin name for flake8
version = __version__ # Plugin version from package metadata
def __init__(self, tree, filename, lines=None):
"""
Initialize flake8 linter.
Args:
tree: Parsed AST of the file
filename: Name of file being checked
lines: File lines (optional, will be loaded from file if None)
"""
@classmethod
def add_options(cls, parser):
"""
Add flake8 command-line options.
Adds options for:
- --application-import-names: Application import names
- --application-package-names: Application package names
- --import-order-style: Import ordering style to use
Args:
parser: Flake8 option parser
"""
@classmethod
def parse_options(cls, options):
"""
Parse and store flake8 options.
Args:
options: Parsed options from flake8
"""
@staticmethod
def list_available_styles():
"""
List available import order styles.
Returns:
Sorted list of available style names
"""
def run(self):
"""
Run import order checking for flake8.
Yields:
Flake8-format error tuples (line, col, message, type)
"""
def error(self, error):
"""
Format error for flake8 output.
Args:
error: Import order error
Returns:
Flake8-format error tuple
"""Pylama linter implementation that integrates import order checking into the pylama linting framework.
class Linter(ImportOrderChecker, BaseLinter):
"""Pylama linter integration for import order checking."""
name = "import-order" # Linter name for pylama
version = __version__ # Linter version from package metadata
def __init__(self):
"""Initialize pylama linter."""
def allow(self, path):
"""
Check if file should be linted.
Args:
path: File path to check
Returns:
True if file should be linted (ends with .py)
"""
def run(self, path, **meta):
"""
Run import order checking for pylama.
Args:
path: File path to check
**meta: Metadata including configuration options
Yields:
Pylama-format error dictionaries
"""
def error(self, error):
"""
Format error for pylama output.
Args:
error: Import order error
Returns:
Pylama-format error dictionary with keys:
- lnum: Line number
- col: Column number (always 0)
- text: Error message
- type: Error code
"""Utility functions for registering options with different versions of flake8.
def register_opt(parser, *args, **kwargs):
"""
Register option with flake8 parser, handling version differences.
Supports both flake8 2.x and 3.x option registration formats.
Args:
parser: Flake8 option parser
*args: Option arguments (e.g., '--option-name')
**kwargs: Option keyword arguments including:
- parse_from_config: Whether to parse from config files
- comma_separated_list: Whether to treat as comma-separated
- default: Default value
- help: Help text
- type: Option type
"""Configure flake8-import-order in setup.cfg or tox.ini:
[flake8]
# Enable import order checking
select = E,W,F,I
# Configure import order style
import-order-style = cryptography
# Specify application import names
application-import-names = myapp,tests,utils
# Specify application package names (for appnexus/edited styles)
application-package-names = mycompany
# Set maximum line length
max-line-length = 88# Run flake8 with import order checking
flake8 --import-order-style=google --application-import-names=myapp myfile.py
# List available styles
flake8 --help | grep import-order-styleConfigure in pylama.ini or setup.cfg:
[pylama]
# Enable import order linter
linters = pyflakes,mccabe,import_order
# Configure import order style
import_order_style = google
# Specify application imports
application_import_names = myapp,testsfrom flake8_import_order.flake8_linter import Linter
import ast
# Set up linter with options
code = '''
import json
import os
from myapp import utils
'''
tree = ast.parse(code)
linter = Linter(tree, 'example.py')
# Configure options
class Options:
application_import_names = ['myapp']
application_package_names = []
import_order_style = 'cryptography'
Linter.parse_options(Options())
# Run linting
for error in linter.run():
line, col, message, error_type = error
print(f"Line {line}: {message}")from flake8_import_order.pylama_linter import Linter
# Create linter instance
linter = Linter()
# Check file
errors = list(linter.run('myfile.py',
import_order_style='google',
application_import_names=['myapp']))
for error in errors:
print(f"Line {error['lnum']}: {error['type']} - {error['text']}")from flake8_import_order.flake8_linter import Linter as FlakeLinter
import ast
class CustomLinter(FlakeLinter):
"""Custom linter with additional features."""
def run(self):
"""Enhanced run method with custom processing."""
errors = list(super().run())
# Add custom processing
if errors:
print(f"Found {len(errors)} import order issues")
return iter(errors)
def error(self, error):
"""Custom error formatting."""
line, col, message, error_type = super().error(error)
# Add custom prefix
custom_message = f"[IMPORT-ORDER] {message}"
return (line, col, custom_message, error_type)The plugin registers itself with flake8 and pylama through setuptools entry points:
# In setup.cfg:
[options.entry_points]
flake8.extension =
I = flake8_import_order.flake8_linter:Linter
pylama.linter =
import_order = flake8_import_order.pylama_linter:LinterBoth integrations support the following configuration options:
The integrations format errors to match their respective framework conventions:
Flake8 Format: (line_number, column_number, "ERROR_CODE message", error_class)
Pylama Format: {"lnum": line_number, "col": column_number, "text": "message", "type": "ERROR_CODE"}
The flake8 integration handles both flake8 2.x and 3.x versions through the register_opt utility function that adapts to different option registration APIs.
Install with Tessl CLI
npx tessl i tessl/pypi-flake8-import-order