Flake8 and pylama plugin that checks the ordering of import statements.
npx @tessl/cli install tessl/pypi-flake8-import-order@0.19.0A flake8 and pylama plugin that checks the ordering of import statements. This plugin enforces proper import grouping and ordering according to various coding style guidelines, helping maintain consistent and readable import organization across Python projects.
pip install flake8-import-orderimport flake8_import_orderFor core data types and enums:
from flake8_import_order import ClassifiedImport, ImportType, NewLineFor AST processing:
from flake8_import_order import ImportVisitorFor utility functions and constants:
from flake8_import_order import get_package_names, root_package_name, STDLIB_NAMES, DEFAULT_IMPORT_ORDER_STYLE# Configuration in setup.cfg or tox.ini
[flake8]
application-import-names = myapp
import-order-style = cryptographyfrom flake8_import_order.checker import ImportOrderChecker
from flake8_import_order.styles import lookup_entry_point
import ast
# Analyze import order in Python code
code = '''
import os
import sys
from myapp import module1
'''
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 import order violations
for error in checker.check_order():
print(f"Line {error.lineno}: {error.code} {error.message}")The plugin architecture consists of several key components:
Essential data structures for representing classified imports, import types, and AST processing utilities for analyzing Python import statements.
# Package metadata (from __about__.py)
__title__ = "flake8-import-order"
__summary__ = "Flake8 and pylama plugin that checks the ordering of import statements."
__uri__ = "https://github.com/PyCQA/flake8-import-order"
__version__ = "0.19.2"
__author__ = "Alex Stapleton"
__email__ = "alexs@prol.etari.at"
__maintainer__ = "Phil Jones"
__maintainer_email__ = "philip.graham.jones+flake8-import@gmail.com"
__license__ = "LGPLv3"
__copyright__ = "Copyright 2013-2016 Alex Stapleton"
# Core data types
ClassifiedImport = namedtuple("ClassifiedImport", [
"type", "is_from", "modules", "names", "lineno",
"end_lineno", "level", "package", "type_checking"
])
class ImportType(IntEnum):
FUTURE = 0
STDLIB = 10
THIRD_PARTY = 20
APPLICATION_PACKAGE = 30
APPLICATION = 40
APPLICATION_RELATIVE = 50
MIXED = -1
def get_package_names(name)
def root_package_name(name)Main checker functionality for validating import order according to configured style rules, including file loading, AST analysis, and error detection.
class ImportOrderChecker:
def __init__(self, filename: str, tree: ast.AST)
def load_file(self) -> None
def check_order(self) -> Iterator[Error]
def error_is_ignored(self, error: Error) -> bool
def parse_comma_separated_list(value: str) -> Set[str]Collection of pre-implemented import ordering styles including cryptography (default), Google, PEP8, and others, with extensible base class for custom styles.
class Style:
accepts_application_package_names: bool = False
def __init__(self, nodes: List[Union[ClassifiedImport, NewLine]])
def check(self) -> Iterator[Error]
def sorted_names(self, names: List[str]) -> List[str]
def import_key(self, import_: ClassifiedImport) -> Tuple
def same_section(self, previous: ClassifiedImport, current: ClassifiedImport) -> bool
def list_entry_points() -> List[EntryPoint]
def lookup_entry_point(name: str) -> EntryPointFlake8 and pylama linter integrations that provide command-line options, configuration parsing, and error formatting for seamless integration with Python linting workflows.
class Linter(ImportOrderChecker): # Flake8 integration
name: str = "import-order"
version: str
def add_options(cls, parser) -> None
def parse_options(cls, options) -> None
def run(self) -> Iterator[Tuple[int, int, str, Type]]
class Linter(ImportOrderChecker, BaseLinter): # Pylama integration
def allow(self, path: str) -> bool
def run(self, path: str, **meta) -> Iterator[Dict[str, Any]]The plugin defines the following error codes:
NewLine = namedtuple("NewLine", ["lineno"])
Error = namedtuple("Error", ["lineno", "code", "message"])
STDLIB_NAMES # Comprehensive set of Python standard library module names
DEFAULT_IMPORT_ORDER_STYLE = "cryptography"