CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-flake8-import-order

Flake8 and pylama plugin that checks the ordering of import statements.

Pending
Overview
Eval results
Files

checker.mddocs/

Import Order Checking and Validation

Main checker functionality for validating import order according to configured style rules, including file loading, AST analysis, and error detection.

Capabilities

Import Order Checker

Main class responsible for analyzing Python files and detecting import order violations according to specified style rules.

class ImportOrderChecker:
    """Main checker class for import order validation."""
    
    visitor_class = ImportVisitor  # AST visitor class to use
    options = None  # Configuration options
    
    def __init__(self, filename, tree):
        """
        Initialize checker with file and AST.
        
        Args:
            filename: Path to file being checked  
            tree: Parsed AST or None to load from file
        """
    
    def load_file(self):
        """
        Load and parse file if not already loaded.
        
        Handles stdin input and regular files, parsing AST if needed.
        """
    
    def check_order(self):
        """
        Check import order and yield errors.
        
        Yields:
            Error objects for each import order violation found
        """
    
    def error_is_ignored(self, error):
        """
        Check if error is ignored via # noqa comment.
        
        Args:
            error: Error to check
            
        Returns:
            True if error should be ignored
        """
    
    def error(self, error):
        """
        Process error for output (override in subclasses).
        
        Args:
            error: Error to process
            
        Returns:
            Processed error object
        """

Configuration and Parsing

Utilities for parsing configuration options and handling comma-separated lists.

def parse_comma_separated_list(value):
    """
    Parse comma-separated configuration values.
    
    Args:
        value: Comma-separated string (e.g., "name1, name2, name3")
    
    Returns:
        Set of stripped, non-empty items
        
    Example:
        parse_comma_separated_list("app1, app2 , app3") -> {"app1", "app2", "app3"}
    """

Error Detection Constants

Regular expressions and constants used for error detection and noqa comment parsing.

DEFAULT_IMPORT_ORDER_STYLE = "cryptography"

NOQA_INLINE_REGEXP = re.compile(
    r"# noqa(?:: (?P<codes>([A-Z][0-9]+(?:[,\s]+)?)+))?",
    re.IGNORECASE,
)
COMMA_SEPARATED_LIST_RE = re.compile(r"[,\s]")
BLANK_LINE_RE = re.compile(r"\s*\n")

Usage Examples

Basic Import Order Checking

from flake8_import_order.checker import ImportOrderChecker
from flake8_import_order.styles import lookup_entry_point
import ast

# Python code to check
code = '''
import sys
import os
from myapp import utils
import json
'''

# Set up checker
tree = ast.parse(code)
checker = ImportOrderChecker('example.py', tree)
checker.options = {
    'application_import_names': ['myapp'],
    'application_package_names': [],
    'import_order_style': lookup_entry_point('cryptography')
}

# Check for violations
for error in checker.check_order():
    print(f"Line {error.lineno}: {error.code} - {error.message}")

File-based Checking

from flake8_import_order.checker import ImportOrderChecker
from flake8_import_order.styles import lookup_entry_point

# Check a Python file
checker = ImportOrderChecker('mymodule.py', None)  # Will load from file
checker.options = {
    'application_import_names': ['myapp', 'myproject'],
    'application_package_names': ['mycompany'],
    'import_order_style': lookup_entry_point('google')
}

# Check for violations
violations = list(checker.check_order())
print(f"Found {len(violations)} import order violations")

Configuration Parsing

from flake8_import_order.checker import parse_comma_separated_list

# Parse configuration values
app_names = parse_comma_separated_list("myapp, tests, utils")
print(app_names)  # {'myapp', 'tests', 'utils'}

# Handle empty values
empty_names = parse_comma_separated_list("")
print(empty_names)  # set()

Custom Checker Subclass

from flake8_import_order.checker import ImportOrderChecker

class CustomChecker(ImportOrderChecker):
    """Custom checker with specialized error handling."""
    
    def error(self, error):
        """Custom error formatting."""
        return {
            'line': error.lineno,
            'code': error.code,
            'message': error.message,
            'severity': 'warning' if error.code.startswith('I2') else 'error'
        }
    
    def check_with_context(self):
        """Check with additional context."""
        errors = []
        for error in self.check_order():
            processed_error = self.error(error)
            errors.append(processed_error)
        return errors

Error Types and Handling

The checker detects several types of import order violations:

Import Ordering Errors

  • I100: Import statements in wrong order within or between groups
  • I666: Mixed import types in single statement

Import Name Ordering Errors

  • I101: Imported names in wrong alphabetical order

Import Group Spacing Errors

  • I201: Missing newline between different import groups
  • I202: Additional newline within same import group
  • I300: Incorrect spacing around TYPE_CHECKING blocks

NOQA Comment Support

The checker supports # noqa comments to ignore specific errors:

import json
import os  # noqa: I100  - Ignore wrong order
from myapp import utils  # noqa  - Ignore all errors on this line

Install with Tessl CLI

npx tessl i tessl/pypi-flake8-import-order

docs

checker.md

core-types.md

index.md

integrations.md

styles.md

tile.json