Skip to content

API

Readability-oriented ordering of Python source code.

rig

Project-specific integrations with pyrig-runtime.

cli

Project-specific command-line support for Python source ordering.

commands

Command implementations for Python source ordering.

check

Command-line checks for Python source ordering.

check_order
check_order(
    files: Iterable[Path], *, fix: bool = False
) -> None

Check order of Python source code.

Parameters:

Name Type Description Default
files Iterable[Path]

Paths to Python source files.

required
fix bool

Whether to apply ordering changes rather than only report them.

False

Raises:

Type Description
Exit

If any file was out of order, even when fix is true.

Source code in src/pyorder/rig/cli/commands/check.py
def check_order(files: Iterable[Path], *, fix: bool = False) -> None:
    """Check order of Python source code.

    Args:
        files: Paths to Python source files.
        fix: Whether to apply ordering changes rather than only report them.

    Raises:
        typer.Exit: If any file was out of order, even when ``fix`` is true.
    """
    if all(tuple(Module.I.check_order(file, fix=fix) for file in files)):
        return

    raise typer.Exit(code=1)

subcommands

Project-specific CLI commands.

Functions defined directly in this module are registered as top-level CLI commands. Module-level typer.Typer instances are registered as command groups, with each group's name derived from the kebab-case form of the variable name.

check
check(
    files: Annotated[
        list[Path], Argument(help="Files to check.")
    ],
    *,
    fix: Annotated[
        bool, Option(help="Automatically fix issues.")
    ] = False
) -> None

Check order of Python source code.

Parameters:

Name Type Description Default
files Annotated[list[Path], Argument(help='Files to check.')]

Paths to Python source files.

required
fix Annotated[bool, Option(help='Automatically fix issues.')]

Whether to apply ordering changes rather than only report them.

False

Raises:

Type Description
Exit

If any file was out of order, even when fix is true.

Source code in src/pyorder/rig/cli/subcommands.py
def check(
    files: Annotated[
        list[Path],
        typer.Argument(
            help="Files to check.",
        ),
    ],
    *,
    fix: Annotated[
        bool,
        typer.Option(
            help="Automatically fix issues.",
        ),
    ] = False,
) -> None:
    """Check order of Python source code.

    Args:
        files: Paths to Python source files.
        fix: Whether to apply ordering changes rather than only report them.

    Raises:
        typer.Exit: If any file was out of order, even when ``fix`` is true.
    """
    from pyorder.rig.cli.commands.check import check_order  # noqa: PLC0415

    check_order(files, fix=fix)

order

Ordering policies and transformations for Python source code.

module

Readability-oriented ordering of definitions in Python modules.

Module

Bases: DependencySubclass

Readability-oriented ordering policies for Python source modules.

abstract_method_rank
abstract_method_rank(
    definition: AnyDefinition,
    _definitions: tuple[AnyDefinition, ...],
) -> SupportsRichComparison

Rank abstract methods before other definitions.

Parameters:

Name Type Description Default
definition AnyDefinition

Definition whose decorators determine the rank.

required
_definitions tuple[AnyDefinition, ...]

Other definitions; not used by this rule.

required

Returns:

Type Description
SupportsRichComparison

Zero if decorated with abstractmethod, otherwise one.

Source code in src/pyorder/rig/order/module.py
def abstract_method_rank(
    self,
    definition: AnyDefinition,
    _definitions: tuple[AnyDefinition, ...],
) -> "SupportsRichComparison":
    """Rank abstract methods before other definitions.

    Args:
        definition: Definition whose decorators determine the rank.
        _definitions: Other definitions; not used by this rule.

    Returns:
        Zero if decorated with ``abstractmethod``, otherwise one.
    """
    if abstractmethod.__name__ in self.decorator_names(definition):
        return 0
    return 1
check_order
check_order(file: Path, *, fix: bool = False) -> bool

Check the order of Python source code in a file.

When fix is false and the file is out of order, show the diff.

Parameters:

Name Type Description Default
file Path

Path to a Python source file.

required
fix bool

Whether to also apply ordering changes.

False

Returns:

Type Description
bool

True if the file is already correctly ordered, False otherwise,

bool

even when ordering changes are applied.

Source code in src/pyorder/rig/order/module.py
    def check_order(self, file: Path, *, fix: bool = False) -> bool:
        """Check the order of Python source code in a file.

        When `fix` is false and the file is out of order, show the diff.

        Args:
            file: Path to a Python source file.
            fix: Whether to also apply ordering changes.

        Returns:
            `True` if the file is already correctly ordered, `False` otherwise,
            even when ordering changes are applied.
        """
        code = self.read_text(file)

        ordered = self.order_code(code)

        if self.is_ordered(code, ordered):
            return True

        if fix:
            self.fix_order(file, ordered)
        else:
            typer.echo(f"""Incorrect order: {file}
{self.diff(code, ordered)}""")
        return False
classes
classes(
    tree: Module | AnyDefinition,
) -> Iterator[AnyDefinition]

Yield direct class definitions from an AST node.

Parameters:

Name Type Description Default
tree Module | AnyDefinition

Parsed module, function, or class to inspect.

required

Yields:

Type Description
AnyDefinition

Direct class definitions in source order.

Source code in src/pyorder/rig/order/module.py
def classes(self, tree: ast.Module | AnyDefinition) -> Iterator[AnyDefinition]:
    """Yield direct class definitions from an AST node.

    Args:
        tree: Parsed module, function, or class to inspect.

    Yields:
        Direct class definitions in source order.
    """
    return (node for node in tree.body if isinstance(node, ast.ClassDef))
classmethod_rank
classmethod_rank(
    definition: AnyDefinition,
    _definitions: tuple[AnyDefinition, ...],
) -> SupportsRichComparison

Rank class methods before other definitions.

Parameters:

Name Type Description Default
definition AnyDefinition

Definition whose decorators determine the rank.

required
_definitions tuple[AnyDefinition, ...]

Other definitions; not used by this rule.

required

Returns:

Type Description
SupportsRichComparison

Zero if decorated with classmethod, otherwise one.

Source code in src/pyorder/rig/order/module.py
def classmethod_rank(
    self,
    definition: AnyDefinition,
    _definitions: tuple[AnyDefinition, ...],
) -> "SupportsRichComparison":
    """Rank class methods before other definitions.

    Args:
        definition: Definition whose decorators determine the rank.
        _definitions: Other definitions; not used by this rule.

    Returns:
        Zero if decorated with ``classmethod``, otherwise one.
    """
    if classmethod.__name__ in self.decorator_names(definition):
        return 0
    return 1
cls_definition_dependencies
cls_definition_dependencies(
    definition: AnyDefinition,
) -> KeysView[str]

Return definition-time dependencies for a class-body definition.

Source code in src/pyorder/rig/order/module.py
def cls_definition_dependencies(self, definition: AnyDefinition) -> KeysView[str]:
    """Return definition-time dependencies for a class-body definition."""
    return self.definition_dependencies(definition)
cls_definition_ranks
cls_definition_ranks() -> tuple[
    Callable[
        [AnyDefinition, tuple[AnyDefinition, ...]],
        SupportsRichComparison,
    ],
    ...,
]

Return the ranking policies for definitions in a class body.

Returns:

Type Description
tuple[Callable[[AnyDefinition, tuple[AnyDefinition, ...]], SupportsRichComparison], ...]

Ranking callables, with earlier entries taking precedence.

Source code in src/pyorder/rig/order/module.py
def cls_definition_ranks(
    self,
) -> tuple[
    Callable[[AnyDefinition, tuple[AnyDefinition, ...]], "SupportsRichComparison"],
    ...,
]:
    """Return the ranking policies for definitions in a class body.

    Returns:
        Ranking callables, with earlier entries taking precedence.
    """
    return (
        self.reverse_definition_kind_rank,
        self.constructor_method_rank,
        self.abstract_method_rank,
        self.override_method_rank,
        self.special_method_rank,
        self.classmethod_rank,
        self.cls_definition_reference_rank,
        *self.standard_definition_ranks(),
    )
cls_definition_reference_rank
cls_definition_reference_rank(
    definition: AnyDefinition,
    definitions: tuple[AnyDefinition, ...],
) -> SupportsRichComparison

Return a class-body definition's reference-layer rank.

Parameters:

Name Type Description Default
definition AnyDefinition

Class-body definition whose rank is required.

required
definitions tuple[AnyDefinition, ...]

Class-body definitions establishing the graph.

required

Returns:

Type Description
SupportsRichComparison

The name's rank, with lower ranks preceding higher ones.

Source code in src/pyorder/rig/order/module.py
def cls_definition_reference_rank(
    self,
    definition: AnyDefinition,
    definitions: tuple[AnyDefinition, ...],
) -> "SupportsRichComparison":
    """Return a class-body definition's reference-layer rank.

    Args:
        definition: Class-body definition whose rank is required.
        definitions: Class-body definitions establishing the graph.

    Returns:
        The name's rank, with lower ranks preceding higher ones.
    """
    return self.definition_reference_rank(
        definition,
        definitions,
        self.cls_definition_references,
        self.cls_definition_dependencies,
    )
cls_definition_references
cls_definition_references(
    definition: AnyDefinition,
) -> KeysView[str]

Collect attributes a method loads from its first parameter or instance.

Parameters:

Name Type Description Default
definition AnyDefinition

Class-body definition whose contents to inspect.

required

Returns:

Type Description
KeysView[str]

Attribute names read directly from the first positional parameter,

KeysView[str]

from a call to it, or from a name assigned that call's result.

Source code in src/pyorder/rig/order/module.py
def cls_definition_references(self, definition: AnyDefinition) -> KeysView[str]:
    """Collect attributes a method loads from its first parameter or instance.

    Args:
        definition: Class-body definition whose contents to inspect.

    Returns:
        Attribute names read directly from the first positional parameter,
        from a call to it, or from a name assigned that call's result.
    """
    if not isinstance(definition, FUNC_DEFINITIONS):
        return dict.fromkeys(()).keys()
    receiver = next(
        (arg.arg for arg in (*definition.args.posonlyargs, *definition.args.args)),
        None,
    )
    instances = {
        target.id
        for node in ast.walk(definition)
        if isinstance(node, (ast.Assign, ast.AnnAssign))
        and isinstance(node.value, ast.Call)
        and isinstance(node.value.func, ast.Name)
        and node.value.func.id == receiver
        for target in (
            node.targets if isinstance(node, ast.Assign) else (node.target,)
        )
        if isinstance(target, ast.Name)
    }
    receivers = instances | {receiver}
    return dict.fromkeys(
        node.attr
        for node in ast.walk(definition)
        if isinstance(node, ast.Attribute)
        and isinstance(node.ctx, ast.Load)
        and (
            (isinstance(node.value, ast.Name) and node.value.id in receivers)
            or (
                isinstance(node.value, ast.Call)
                and isinstance(node.value.func, ast.Name)
                and node.value.func.id == receiver
            )
        )
    ).keys()
constructor_method_rank
constructor_method_rank(
    definition: AnyDefinition,
    _definitions: tuple[AnyDefinition, ...],
) -> SupportsRichComparison

Rank object's constructor hooks in call order before other definitions.

Parameters:

Name Type Description Default
definition AnyDefinition

Definition whose name determines the rank.

required
_definitions tuple[AnyDefinition, ...]

Other definitions; not used by this rule.

required

Returns:

Type Description
SupportsRichComparison

Zero for __init_subclass__, one for __new__, two for

SupportsRichComparison

__init__, and three otherwise.

Source code in src/pyorder/rig/order/module.py
def constructor_method_rank(
    self,
    definition: AnyDefinition,
    _definitions: tuple[AnyDefinition, ...],
) -> "SupportsRichComparison":
    """Rank object's constructor hooks in call order before other definitions.

    Args:
        definition: Definition whose name determines the rank.
        _definitions: Other definitions; not used by this rule.

    Returns:
        Zero for ``__init_subclass__``, one for ``__new__``, two for
        ``__init__``, and three otherwise.
    """
    name = definition.name
    return (
        object.__init_subclass__.__name__,
        object.__new__.__name__,
        object.__init__.__name__,
        name,
    ).index(name)
decode_source
decode_source(source: bytes) -> str

Decode UTF-8 source bytes.

Parameters:

Name Type Description Default
source bytes

UTF-8 encoded source.

required

Returns:

Type Description
str

The decoded source.

Source code in src/pyorder/rig/order/module.py
def decode_source(self, source: bytes) -> str:
    """Decode UTF-8 source bytes.

    Args:
        source: UTF-8 encoded source.

    Returns:
        The decoded source.
    """
    return source.decode(SOURCE_ENCODING)
decorator_names
decorator_names(definition: AnyDefinition) -> Iterator[str]

Return the final names of plain name and attribute decorators.

Called decorators and other expressions are ignored.

Parameters:

Name Type Description Default
definition AnyDefinition

Definition whose decorators to inspect.

required

Returns:

Type Description
Iterator[str]

Names such as name for @name and attr for @obj.attr.

Source code in src/pyorder/rig/order/module.py
def decorator_names(self, definition: AnyDefinition) -> Iterator[str]:
    """Return the final names of plain name and attribute decorators.

    Called decorators and other expressions are ignored.

    Args:
        definition: Definition whose decorators to inspect.

    Returns:
        Names such as ``name`` for ``@name`` and ``attr`` for ``@obj.attr``.
    """
    return (
        decorator.id if isinstance(decorator, ast.Name) else decorator.attr
        for decorator in definition.decorator_list
        if isinstance(decorator, (ast.Name, ast.Attribute))
    )
definition_dependencies
definition_dependencies(
    definition: AnyDefinition,
) -> KeysView[str]

Collect definition-time names, excluding annotations.

Inspect decorators, defaults, class headers, and class-suite statements. Ignore annotations, deferred function, lambda, and generator bodies, and type-alias statements. Conditional branches are included without resolving names across scopes or through calls.

Parameters:

Name Type Description Default
definition AnyDefinition

Definition whose dependencies to collect.

required

Returns:

Type Description
KeysView[str]

Names referenced by the definition-time expressions inspected.

Source code in src/pyorder/rig/order/module.py
def definition_dependencies(self, definition: AnyDefinition) -> KeysView[str]:
    """Collect definition-time names, excluding annotations.

    Inspect decorators, defaults, class headers, and class-suite statements.
    Ignore annotations, deferred function, lambda, and generator bodies,
    and type-alias statements. Conditional branches are included without
    resolving names across scopes or through calls.

    Args:
        definition: Definition whose dependencies to collect.

    Returns:
        Names referenced by the definition-time expressions inspected.
    """
    pending: list[ast.AST] = [definition]
    dependencies: dict[str, None] = {}
    while pending:
        node = pending.pop()
        if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load):
            dependencies[node.id] = None
        if isinstance(node, ast.AugAssign) and isinstance(node.target, ast.Name):
            dependencies[node.target.id] = None
        pending.extend(self.definition_dependency_children(node))
    return dependencies.keys()
definition_dependency_children
definition_dependency_children(node: AST) -> Iterator[AST]

Yield AST children used to inspect definition-time evaluation.

Parameters:

Name Type Description Default
node AST

Node whose evaluation boundaries determine its children.

required

Yields:

Type Description
AST

Children to inspect, excluding annotations and deferred bodies.

Source code in src/pyorder/rig/order/module.py
def definition_dependency_children(self, node: ast.AST) -> Iterator[ast.AST]:
    """Yield AST children used to inspect definition-time evaluation.

    Args:
        node: Node whose evaluation boundaries determine its children.

    Yields:
        Children to inspect, excluding annotations and deferred bodies.
    """
    if isinstance(node, ast.ClassDef):
        yield from node.decorator_list
        yield from node.bases
        yield from (keyword.value for keyword in node.keywords)
        yield from node.body
    elif isinstance(node, (*FUNC_DEFINITIONS, ast.Lambda)):
        if isinstance(node, FUNC_DEFINITIONS):
            yield from node.decorator_list
        yield from node.args.defaults
        yield from filter(None, node.args.kw_defaults)
    elif isinstance(node, ast.GeneratorExp):
        yield node.generators[0].iter
    elif isinstance(node, ast.AnnAssign):
        yield node.target
        if node.value is not None:
            yield node.value
    elif not isinstance(node, ast.TypeAlias):
        yield from ast.iter_child_nodes(node)
definition_kind_rank
definition_kind_rank(
    definition: AnyDefinition,
    _definitions: tuple[AnyDefinition, ...],
) -> int

Rank functions before classes.

Parameters:

Name Type Description Default
definition AnyDefinition

Definition whose kind determines the rank.

required
_definitions tuple[AnyDefinition, ...]

Other definitions; not used by this rule.

required

Returns:

Type Description
int

Zero for functions and one for classes.

Source code in src/pyorder/rig/order/module.py
def definition_kind_rank(
    self,
    definition: AnyDefinition,
    _definitions: tuple[AnyDefinition, ...],
) -> int:
    """Rank functions before classes.

    Args:
        definition: Definition whose kind determines the rank.
        _definitions: Other definitions; not used by this rule.

    Returns:
        Zero for functions and one for classes.
    """
    if isinstance(definition, FUNC_DEFINITIONS):
        return 0
    return 1
definition_name_rank
definition_name_rank(
    definition: AnyDefinition,
    _definitions: tuple[AnyDefinition, ...],
) -> str

Return the unchanged name for case-sensitive alphabetical ordering.

Parameters:

Name Type Description Default
definition AnyDefinition

Definition whose name determines the rank.

required
_definitions tuple[AnyDefinition, ...]

Other definitions; not used by this rule.

required

Returns:

Type Description
str

The definition's name.

Source code in src/pyorder/rig/order/module.py
def definition_name_rank(
    self,
    definition: AnyDefinition,
    _definitions: tuple[AnyDefinition, ...],
) -> str:
    """Return the unchanged name for case-sensitive alphabetical ordering.

    Args:
        definition: Definition whose name determines the rank.
        _definitions: Other definitions; not used by this rule.

    Returns:
        The definition's name.
    """
    return definition.name
definition_reference_rank
definition_reference_rank(
    definition: AnyDefinition,
    definitions: tuple[AnyDefinition, ...],
    references: Callable[[AnyDefinition], KeysView[str]],
    dependencies: Callable[[AnyDefinition], KeysView[str]],
) -> int

Return the reference-layer rank associated with a definition's name.

Parameters:

Name Type Description Default
definition AnyDefinition

Definition whose rank is required.

required
definitions tuple[AnyDefinition, ...]

Definitions that establish the reference relationships.

required
references Callable[[AnyDefinition], KeysView[str]]

Function to extract references from a definition.

required
dependencies Callable[[AnyDefinition], KeysView[str]]

Function to extract dependencies from a definition.

required

Returns:

Type Description
int

The name's rank, with lower ranks preceding higher ones.

Source code in src/pyorder/rig/order/module.py
def definition_reference_rank(
    self,
    definition: AnyDefinition,
    definitions: tuple[AnyDefinition, ...],
    references: Callable[[AnyDefinition], KeysView[str]],
    dependencies: Callable[[AnyDefinition], KeysView[str]],
) -> int:
    """Return the reference-layer rank associated with a definition's name.

    Args:
        definition: Definition whose rank is required.
        definitions: Definitions that establish the reference relationships.
        references: Function to extract references from a definition.
        dependencies: Function to extract dependencies from a definition.

    Returns:
        The name's rank, with lower ranks preceding higher ones.
    """
    return self.definition_reference_ranks(
        definitions,
        references,
        dependencies,
    )[definition.name]
definition_reference_ranks cached classmethod
definition_reference_ranks(
    definitions: tuple[AnyDefinition, ...],
    references: Callable[[AnyDefinition], KeysView[str]],
    dependencies: Callable[[AnyDefinition], KeysView[str]],
) -> dict[str, int]

Group definition names into top-down reference layers.

Users precede their references, but definition-time dependencies precede their users. Only names in definitions contribute. Within cycles containing dependencies, discard internal reference-only edges. Reference-only cycles and unavoidable dependency cycles share a rank.

Parameters:

Name Type Description Default
definitions tuple[AnyDefinition, ...]

Definitions to rank together.

required
references Callable[[AnyDefinition], KeysView[str]]

Collector of names referenced by a definition.

required
dependencies Callable[[AnyDefinition], KeysView[str]]

Collector of names needed when a definition is created.

required

Returns:

Type Description
dict[str, int]

Name-to-layer mapping, starting at zero. Lower layers come first;

dict[str, int]

names in the same layer tie. Treat the cached mapping as read-only.

Source code in src/pyorder/rig/order/module.py
@classmethod
@lru_cache(maxsize=1)
def definition_reference_ranks(
    cls,
    definitions: tuple[AnyDefinition, ...],
    references: Callable[[AnyDefinition], KeysView[str]],
    dependencies: Callable[[AnyDefinition], KeysView[str]],
) -> dict[str, int]:
    """Group definition names into top-down reference layers.

    Users precede their references, but definition-time dependencies precede
    their users. Only names in ``definitions`` contribute. Within cycles
    containing dependencies, discard internal reference-only edges.
    Reference-only cycles and unavoidable dependency cycles share a rank.

    Args:
        definitions: Definitions to rank together.
        references: Collector of names referenced by a definition.
        dependencies: Collector of names needed when a definition is created.

    Returns:
        Name-to-layer mapping, starting at zero. Lower layers come first;
        names in the same layer tie. Treat the cached mapping as read-only.
    """
    names = {definition.name for definition in definitions}
    graph = nx.DiGraph()
    graph.add_nodes_from(names)
    dependency_edges, reference_edges = set(), set()
    for definition in definitions:
        used = references(definition) & names
        needed = dependencies(definition) & names
        reference_edges.update((definition.name, name) for name in used - needed)
        dependency_edges.update((name, definition.name) for name in needed)
    graph.add_edges_from(reference_edges)
    graph.add_edges_from(dependency_edges)

    for component in tuple(nx.strongly_connected_components(graph)):
        if (edges := set(graph.subgraph(component).edges)) & dependency_edges:
            graph.remove_edges_from(edges - dependency_edges)

    condensed = nx.condensation(graph)
    return {
        name: rank
        for rank, generation in enumerate(nx.topological_generations(condensed))
        for component in generation
        for name in condensed.nodes[component]["members"]
    }
definition_sort_key
definition_sort_key(
    definition: AnyDefinition,
    definitions: tuple[AnyDefinition, ...],
    ranks: tuple[
        Callable[
            [AnyDefinition, tuple[AnyDefinition, ...]],
            SupportsRichComparison,
        ],
        ...,
    ],
) -> tuple[SupportsRichComparison, ...]

Return the policy values used to sort a definition.

Parameters:

Name Type Description Default
definition AnyDefinition

Definition to rank.

required
definitions tuple[AnyDefinition, ...]

All definitions participating in the sort.

required
ranks tuple[Callable[[AnyDefinition, tuple[AnyDefinition, ...]], SupportsRichComparison], ...]

Ranking rules used to produce the key.

required

Returns:

Type Description
tuple[SupportsRichComparison, ...]

A lexicographic key whose earlier values take precedence.

Source code in src/pyorder/rig/order/module.py
def definition_sort_key(
    self,
    definition: AnyDefinition,
    definitions: tuple[AnyDefinition, ...],
    ranks: tuple[
        Callable[
            [AnyDefinition, tuple[AnyDefinition, ...]],
            "SupportsRichComparison",
        ],
        ...,
    ],
) -> tuple["SupportsRichComparison", ...]:
    """Return the policy values used to sort a definition.

    Args:
        definition: Definition to rank.
        definitions: All definitions participating in the sort.
        ranks: Ranking rules used to produce the key.

    Returns:
        A lexicographic key whose earlier values take precedence.
    """
    return tuple(key(definition, definitions) for key in ranks)
definition_visibility_rank
definition_visibility_rank(
    definition: AnyDefinition,
    _definitions: tuple[AnyDefinition, ...],
) -> int

Rank names by their number of leading underscores, fewest first.

Dunder names receive no special treatment.

Parameters:

Name Type Description Default
definition AnyDefinition

Definition whose name determines the rank.

required
_definitions tuple[AnyDefinition, ...]

Other definitions; unused by this rule.

required

Returns:

Type Description
int

The number of leading underscores in the name.

Source code in src/pyorder/rig/order/module.py
def definition_visibility_rank(
    self,
    definition: AnyDefinition,
    _definitions: tuple[AnyDefinition, ...],
) -> int:
    """Rank names by their number of leading underscores, fewest first.

    Dunder names receive no special treatment.

    Args:
        definition: Definition whose name determines the rank.
        _definitions: Other definitions; unused by this rule.

    Returns:
        The number of leading underscores in the name.
    """
    name = definition.name
    return len(name) - len(name.lstrip("_"))
definitions
definitions(
    tree: Module | AnyDefinition,
) -> Iterator[AnyDefinition]

Yield direct function and class definitions from an AST node.

Parameters:

Name Type Description Default
tree Module | AnyDefinition

Parsed module, function, or class to inspect.

required

Yields:

Type Description
AnyDefinition

Synchronous functions, asynchronous functions, and classes in

AnyDefinition

source order, excluding definitions nested in other statements.

Source code in src/pyorder/rig/order/module.py
def definitions(self, tree: ast.Module | AnyDefinition) -> Iterator[AnyDefinition]:
    """Yield direct function and class definitions from an AST node.

    Args:
        tree: Parsed module, function, or class to inspect.

    Yields:
        Synchronous functions, asynchronous functions, and classes in
        source order, excluding definitions nested in other statements.
    """
    return (node for node in tree.body if isinstance(node, DEFINITIONS))
diff
diff(unordered: str, ordered: str) -> str

Return a unified line diff between unordered and ordered source.

Parameters:

Name Type Description Default
unordered str

Original source.

required
ordered str

Source to compare against the original.

required

Returns:

Type Description
str

The diff text, or an empty string if the split lines match.

Source code in src/pyorder/rig/order/module.py
def diff(self, unordered: str, ordered: str) -> str:
    """Return a unified line diff between unordered and ordered source.

    Args:
        unordered: Original source.
        ordered: Source to compare against the original.

    Returns:
        The diff text, or an empty string if the split lines match.
    """
    return "\n".join(
        difflib.unified_diff(
            unordered.splitlines(),
            ordered.splitlines(),
            lineterm="",
        ),
    )
discovery_module classmethod
discovery_module() -> ModuleType

Return the package that scopes subclass discovery.

Source code in src/pyorder/rig/order/module.py
@classmethod
@override
def discovery_module(cls) -> ModuleType:
    """Return the package that scopes subclass discovery."""
    return order
encode_source
encode_source(code: str) -> bytes

Encode source as UTF-8, matching the AST's byte offsets.

Parameters:

Name Type Description Default
code str

Source to encode.

required

Returns:

Type Description
bytes

The UTF-8 encoded source.

Source code in src/pyorder/rig/order/module.py
def encode_source(self, code: str) -> bytes:
    """Encode source as UTF-8, matching the AST's byte offsets.

    Args:
        code: Source to encode.

    Returns:
        The UTF-8 encoded source.
    """
    return code.encode(SOURCE_ENCODING)
file_info
file_info(file: Path) -> tuple[str, str]

Detect the source encoding and newline sequence.

Read one line; buffering may detect newlines beyond that line. If multiple styles are detected, use the first reported style.

Parameters:

Name Type Description Default
file Path

Path to an existing Python source file.

required

Returns:

Type Description
str

A pair of the encoding name and newline sequence. The sequence

str

defaults to LF if no line terminator is detected.

Source code in src/pyorder/rig/order/module.py
def file_info(self, file: Path) -> tuple[str, str]:
    """Detect the source encoding and newline sequence.

    Read one line; buffering may detect newlines beyond that line.
    If multiple styles are detected, use the first reported style.

    Args:
        file: Path to an existing Python source file.

    Returns:
        A pair of the encoding name and newline sequence. The sequence
        defaults to LF if no line terminator is detected.
    """
    with tokenize.open(file) as f:
        f.readline()
        newlines = f.newlines
        newline = (
            newlines
            if isinstance(newlines, str)
            else next(iter(newlines or ()), "\n")
        )
        return f.encoding, newline
fix_order
fix_order(file: Path, code: str) -> None

Write replacement source to an existing file.

Parameters:

Name Type Description Default
file Path

Existing destination file.

required
code str

Replacement source with LF-normalized line endings.

required
Source code in src/pyorder/rig/order/module.py
def fix_order(self, file: Path, code: str) -> None:
    """Write replacement source to an existing file.

    Args:
        file: Existing destination file.
        code: Replacement source with LF-normalized line endings.
    """
    self.write_text(file, code)
is_ordered
is_ordered(unordered: str, ordered: str) -> bool

Return whether the source matches its expected ordering.

Parameters:

Name Type Description Default
unordered str

Source being checked.

required
ordered str

Expected source.

required

Returns:

Type Description
bool

Whether both strings are equal, including whitespace.

Source code in src/pyorder/rig/order/module.py
def is_ordered(self, unordered: str, ordered: str) -> bool:
    """Return whether the source matches its expected ordering.

    Args:
        unordered: Source being checked.
        ordered: Expected source.

    Returns:
        Whether both strings are equal, including whitespace.
    """
    return unordered == ordered
line_offsets
line_offsets(lines: list[bytes]) -> tuple[int, ...]

Return the byte offset at which each line starts.

Parameters:

Name Type Description Default
lines list[bytes]

UTF-8 encoded source lines, with line endings kept.

required

Returns:

Type Description
tuple[int, ...]

Start offsets for every line, followed by the total source length.

Source code in src/pyorder/rig/order/module.py
def line_offsets(self, lines: list[bytes]) -> tuple[int, ...]:
    """Return the byte offset at which each line starts.

    Args:
        lines: UTF-8 encoded source lines, with line endings kept.

    Returns:
        Start offsets for every line, followed by the total source length.
    """
    return tuple(accumulate(map(len, lines), initial=0))
merge_key classmethod
merge_key() -> Hashable

Return a key for merging subclasses of this class.

Use a constant key so Module subclasses are merged together.

Returns:

Type Description
Hashable

The string representation of the Module class.

Source code in src/pyorder/rig/order/module.py
@classmethod
@override
def merge_key(cls) -> Hashable:
    """Return a key for merging subclasses of this class.

    Use a constant key so Module subclasses are merged together.

    Returns:
        The string representation of the Module class.
    """
    return str(Module)
module_definition_dependencies
module_definition_dependencies(
    definition: AnyDefinition,
) -> KeysView[str]

Return definition-time dependencies for a module-level definition.

Source code in src/pyorder/rig/order/module.py
def module_definition_dependencies(
    self,
    definition: AnyDefinition,
) -> KeysView[str]:
    """Return definition-time dependencies for a module-level definition."""
    return self.definition_dependencies(definition)
module_definition_ranks
module_definition_ranks() -> tuple[
    Callable[
        [AnyDefinition, tuple[AnyDefinition, ...]],
        SupportsRichComparison,
    ],
    ...,
]

Return the ordered policies used to rank module-level definitions.

Each rule takes a definition and the full set of definitions, returning a comparable value. Earlier rules have higher priority.

Returns:

Type Description
tuple[Callable[[AnyDefinition, tuple[AnyDefinition, ...]], SupportsRichComparison], ...]

Tuple of ranking rules represented as callables.

Source code in src/pyorder/rig/order/module.py
def module_definition_ranks(
    self,
) -> tuple[
    Callable[[AnyDefinition, tuple[AnyDefinition, ...]], "SupportsRichComparison"],
    ...,
]:
    """Return the ordered policies used to rank module-level definitions.

    Each rule takes a definition and the full set of definitions, returning
    a comparable value. Earlier rules have higher priority.

    Returns:
        Tuple of ranking rules represented as callables.
    """
    return (
        self.module_definition_reference_rank,
        self.definition_kind_rank,
        *self.standard_definition_ranks(),
    )
module_definition_reference_rank
module_definition_reference_rank(
    definition: AnyDefinition,
    definitions: tuple[AnyDefinition, ...],
) -> int

Return a module-level definition's reference-layer rank.

Parameters:

Name Type Description Default
definition AnyDefinition

Module-level definition whose rank is required.

required
definitions tuple[AnyDefinition, ...]

Module-level definitions establishing the graph.

required

Returns:

Type Description
int

The name's rank, with lower ranks preceding higher ones.

Source code in src/pyorder/rig/order/module.py
def module_definition_reference_rank(
    self,
    definition: AnyDefinition,
    definitions: tuple[AnyDefinition, ...],
) -> int:
    """Return a module-level definition's reference-layer rank.

    Args:
        definition: Module-level definition whose rank is required.
        definitions: Module-level definitions establishing the graph.

    Returns:
        The name's rank, with lower ranks preceding higher ones.
    """
    return self.definition_reference_rank(
        definition,
        definitions,
        self.module_definition_references,
        self.module_definition_dependencies,
    )
module_definition_references
module_definition_references(
    definition: AnyDefinition,
) -> KeysView[str]

Collect names loaded anywhere in a definition's syntax tree.

Parameters:

Name Type Description Default
definition AnyDefinition

Definition whose contents to inspect.

required

Returns:

Type Description
KeysView[str]

Loaded names found anywhere in the definition's syntax tree.

Source code in src/pyorder/rig/order/module.py
def module_definition_references(self, definition: AnyDefinition) -> KeysView[str]:
    """Collect names loaded anywhere in a definition's syntax tree.

    Args:
        definition: Definition whose contents to inspect.

    Returns:
        Loaded names found anywhere in the definition's syntax tree.
    """
    return dict.fromkeys(
        node.id
        for node in ast.walk(definition)
        if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load)
    ).keys()
order_code
order_code(code: str) -> str

Return source with the module's ordering policies applied.

Parameters:

Name Type Description Default
code str

Python source to reorder.

required

Returns:

Type Description
str

Transformed and ordered source code.

Source code in src/pyorder/rig/order/module.py
def order_code(self, code: str) -> str:
    """Return source with the module's ordering policies applied.

    Args:
        code: Python source to reorder.

    Returns:
        Transformed and ordered source code.
    """
    for reorder in self.reorderers():
        code = reorder(code, ast.parse(code))
    return code
order_definitions
order_definitions(
    definitions: tuple[AnyDefinition, ...],
    ranks: tuple[
        Callable[
            [AnyDefinition, tuple[AnyDefinition, ...]],
            SupportsRichComparison,
        ],
        ...,
    ],
) -> list[AnyDefinition]

Return definitions in stable, ascending policy-key order.

Parameters:

Name Type Description Default
definitions tuple[AnyDefinition, ...]

Definitions to sort together.

required
ranks tuple[Callable[[AnyDefinition, tuple[AnyDefinition, ...]], SupportsRichComparison], ...]

Ranking rules applied in tuple order.

required

Returns:

Type Description
list[AnyDefinition]

A sorted list retaining original order when keys compare equal.

Source code in src/pyorder/rig/order/module.py
def order_definitions(
    self,
    definitions: tuple[AnyDefinition, ...],
    ranks: tuple[
        Callable[
            [AnyDefinition, tuple[AnyDefinition, ...]],
            "SupportsRichComparison",
        ],
        ...,
    ],
) -> list[AnyDefinition]:
    """Return definitions in stable, ascending policy-key order.

    Args:
        definitions: Definitions to sort together.
        ranks: Ranking rules applied in tuple order.

    Returns:
        A sorted list retaining original order when keys compare equal.
    """

    def sort_key(definition: AnyDefinition) -> tuple["SupportsRichComparison", ...]:
        return self.definition_sort_key(
            definition,
            definitions,
            ranks,
        )

    return sorted(
        definitions,
        key=sort_key,
    )
override_method_rank
override_method_rank(
    definition: AnyDefinition,
    _definitions: tuple[AnyDefinition, ...],
) -> SupportsRichComparison

Rank explicitly overridden methods before other definitions.

Parameters:

Name Type Description Default
definition AnyDefinition

Definition whose decorators determine the rank.

required
_definitions tuple[AnyDefinition, ...]

Other definitions; not used by this rule.

required

Returns:

Type Description
SupportsRichComparison

Zero if decorated with override, otherwise one.

Source code in src/pyorder/rig/order/module.py
def override_method_rank(
    self,
    definition: AnyDefinition,
    _definitions: tuple[AnyDefinition, ...],
) -> "SupportsRichComparison":
    """Rank explicitly overridden methods before other definitions.

    Args:
        definition: Definition whose decorators determine the rank.
        _definitions: Other definitions; not used by this rule.

    Returns:
        Zero if decorated with ``override``, otherwise one.
    """
    if override.__name__ in self.decorator_names(definition):
        return 0
    return 1
read_text
read_text(file: Path) -> str

Read Python source using its detected encoding.

Parameters:

Name Type Description Default
file Path

Path to an existing Python source file.

required

Returns:

Type Description
str

The decoded contents with line endings normalized to LF and any

str

leading UTF-8 byte-order mark removed.

Source code in src/pyorder/rig/order/module.py
def read_text(self, file: Path) -> str:
    """Read Python source using its detected encoding.

    Args:
        file: Path to an existing Python source file.

    Returns:
        The decoded contents with line endings normalized to LF and any
        leading UTF-8 byte-order mark removed.
    """
    encoding, _ = self.file_info(file)
    return file.read_text(encoding=encoding)
reorder_cls_definitions
reorder_cls_definitions(code: str, module: Module) -> str

Reorder definitions directly in each module-level class body.

Parameters:

Name Type Description Default
code str

Python source corresponding to module.

required
module Module

Parsed module containing the classes to process.

required

Returns:

Type Description
str

Source with each module-level class body ordered by its policies.

Source code in src/pyorder/rig/order/module.py
def reorder_cls_definitions(self, code: str, module: ast.Module) -> str:
    """Reorder definitions directly in each module-level class body.

    Args:
        code: Python source corresponding to ``module``.
        module: Parsed module containing the classes to process.

    Returns:
        Source with each module-level class body ordered by its policies.
    """
    for cls in self.classes(module):
        code = self.reorder_definitions(
            code,
            self.definitions(cls),
            self.cls_definition_ranks(),
        )
    return code
reorder_code
reorder_code(
    code: str,
    unordered: Iterable[stmt],
    ordered: Iterable[stmt],
) -> str

Replace selected source segments with their requested ordering.

Compute each span once and replace from the end to keep offsets valid.

Parameters:

Name Type Description Default
code str

Original source from which the nodes were parsed.

required
unordered Iterable[stmt]

Nodes in their original source order.

required
ordered Iterable[stmt]

The same nodes in the desired order.

required

Returns:

Type Description
str

Source with the selected segments replaced in the requested order.

Source code in src/pyorder/rig/order/module.py
def reorder_code(
    self,
    code: str,
    unordered: Iterable[ast.stmt],
    ordered: Iterable[ast.stmt],
) -> str:
    """Replace selected source segments with their requested ordering.

    Compute each span once and replace from the end to keep offsets valid.

    Args:
        code: Original source from which the nodes were parsed.
        unordered: Nodes in their original source order.
        ordered: The same nodes in the desired order.

    Returns:
        Source with the selected segments replaced in the requested order.
    """
    source = self.encode_source(code)
    lines = self.source_lines(source)
    offsets = self.line_offsets(lines)
    spans = {node: self.source_span(lines, offsets, node) for node in unordered}
    ordered_sources = tuple(
        source[start:end] for start, end in (spans[node] for node in ordered)
    )
    for (start, end), replacement in reversed(
        tuple(zip(spans.values(), ordered_sources, strict=True)),
    ):
        source = source[:start] + replacement + source[end:]
    return self.decode_source(source)
reorder_definitions
reorder_definitions(
    code: str,
    definitions: Iterable[AnyDefinition],
    ranks: tuple[
        Callable[
            [AnyDefinition, tuple[AnyDefinition, ...]],
            SupportsRichComparison,
        ],
        ...,
    ],
) -> str

Reorder the supplied definitions according to their ranking policies.

Nested definitions are not independently reordered.

Parameters:

Name Type Description Default
code str

Python source code.

required
definitions Iterable[AnyDefinition]

Definitions to reorder.

required
ranks tuple[Callable[[AnyDefinition, tuple[AnyDefinition, ...]], SupportsRichComparison], ...]

Ranking policies applied in priority order.

required

Returns:

Type Description
str

Source with reordered definitions according to the ordering policies.

Source code in src/pyorder/rig/order/module.py
def reorder_definitions(
    self,
    code: str,
    definitions: Iterable[AnyDefinition],
    ranks: tuple[
        Callable[
            [AnyDefinition, tuple[AnyDefinition, ...]],
            "SupportsRichComparison",
        ],
        ...,
    ],
) -> str:
    """Reorder the supplied definitions according to their ranking policies.

    Nested definitions are not independently reordered.

    Args:
        code: Python source code.
        definitions: Definitions to reorder.
        ranks: Ranking policies applied in priority order.

    Returns:
        Source with reordered definitions according to the ordering policies.
    """
    definitions = tuple(definitions)
    return self.reorder_code(
        code,
        definitions,
        self.order_definitions(definitions, ranks),
    )
reorder_module_definitions
reorder_module_definitions(
    code: str, module: Module
) -> str

Reorder definitions directly in the module body.

Parameters:

Name Type Description Default
code str

Python source corresponding to module.

required
module Module

Parsed module whose direct definitions are reordered.

required

Returns:

Type Description
str

Source with module-level definitions ordered by their policies.

Source code in src/pyorder/rig/order/module.py
def reorder_module_definitions(self, code: str, module: ast.Module) -> str:
    """Reorder definitions directly in the module body.

    Args:
        code: Python source corresponding to ``module``.
        module: Parsed module whose direct definitions are reordered.

    Returns:
        Source with module-level definitions ordered by their policies.
    """
    return self.reorder_definitions(
        code,
        self.definitions(module),
        self.module_definition_ranks(),
    )
reorderers
reorderers() -> tuple[Callable[[str, Module], str], ...]

Return the source-reordering passes in application order.

Returns:

Type Description
tuple[Callable[[str, Module], str], ...]

Module-level definition ordering followed by class-body ordering.

Source code in src/pyorder/rig/order/module.py
def reorderers(self) -> tuple[Callable[[str, ast.Module], str], ...]:
    """Return the source-reordering passes in application order.

    Returns:
        Module-level definition ordering followed by class-body ordering.
    """
    return (
        self.reorder_module_definitions,
        self.reorder_cls_definitions,
    )
reverse_definition_kind_rank
reverse_definition_kind_rank(
    definition: AnyDefinition,
    definitions: tuple[AnyDefinition, ...],
) -> int

Rank classes before functions.

Parameters:

Name Type Description Default
definition AnyDefinition

Definition whose kind determines the rank.

required
definitions tuple[AnyDefinition, ...]

Other definitions, passed to definition_kind_rank.

required

Returns:

Type Description
int

Minus one for classes and zero for functions.

Source code in src/pyorder/rig/order/module.py
def reverse_definition_kind_rank(
    self,
    definition: AnyDefinition,
    definitions: tuple[AnyDefinition, ...],
) -> int:
    """Rank classes before functions.

    Args:
        definition: Definition whose kind determines the rank.
        definitions: Other definitions, passed to ``definition_kind_rank``.

    Returns:
        Minus one for classes and zero for functions.
    """
    return -self.definition_kind_rank(definition, definitions)
source_lines
source_lines(source: bytes) -> list[bytes]

Split encoded source into lines, keeping line endings.

Parameters:

Name Type Description Default
source bytes

UTF-8 encoded source.

required

Returns:

Type Description
list[bytes]

The source lines with any existing line endings preserved.

Source code in src/pyorder/rig/order/module.py
def source_lines(self, source: bytes) -> list[bytes]:
    """Split encoded source into lines, keeping line endings.

    Args:
        source: UTF-8 encoded source.

    Returns:
        The source lines with any existing line endings preserved.
    """
    return source.splitlines(keepends=True)
source_span
source_span(
    lines: list[bytes], offsets: tuple[int, ...], node: stmt
) -> tuple[int, int]

Return a node's start and exclusive end as UTF-8 byte offsets.

Include decorators and final inline comments without modifying the node.

Parameters:

Name Type Description Default
lines list[bytes]

UTF-8 encoded source lines, with line endings kept, corresponding to the node's locations.

required
offsets tuple[int, ...]

Byte offset of each line's start, as from line_offsets.

required
node stmt

Parsed statement whose source segment is required.

required

Returns:

Type Description
int

Byte offsets into the joined lines, enclosing the node and its

int

final inline comment.

Raises:

Type Description
LookupError

If the statement lacks end locations.

Source code in src/pyorder/rig/order/module.py
def source_span(
    self,
    lines: list[bytes],
    offsets: tuple[int, ...],
    node: ast.stmt,
) -> tuple[int, int]:
    """Return a node's start and exclusive end as UTF-8 byte offsets.

    Include decorators and final inline comments without modifying the node.

    Args:
        lines: UTF-8 encoded source lines, with line endings kept,
            corresponding to the node's locations.
        offsets: Byte offset of each line's start, as from ``line_offsets``.
        node: Parsed statement whose source segment is required.

    Returns:
        Byte offsets into the joined ``lines``, enclosing the node and its
        final inline comment.

    Raises:
        LookupError: If the statement lacks end locations.
    """
    col_offset = node.col_offset
    if (end_lineno := node.end_lineno) is None or (
        end_col_offset := node.end_col_offset
    ) is None:
        msg = f"failed to get source span {node=}"
        raise LookupError(msg)
    lineno = node.lineno - 1
    end_lineno = end_lineno - 1
    if isinstance(node, DEFINITIONS) and (decorator_list := node.decorator_list):
        lineno = decorator_list[0].lineno - 1
        while not lines[lineno].lstrip(b" \t\f").startswith(b"@"):
            lineno -= 1
        col_offset = lines[lineno].index(b"@")
    end_line = lines[end_lineno].rstrip(b"\r\n")
    if end_line[end_col_offset:].lstrip(b" \t\f").startswith(b"#"):
        end_col_offset = len(end_line)
    return (
        offsets[lineno] + col_offset,
        offsets[end_lineno] + end_col_offset,
    )
special_method_rank
special_method_rank(
    definition: AnyDefinition,
    _definitions: tuple[AnyDefinition, ...],
) -> SupportsRichComparison

Rank dunder names before other definitions.

Parameters:

Name Type Description Default
definition AnyDefinition

Definition whose name determines the rank.

required
_definitions tuple[AnyDefinition, ...]

Other definitions; not used by this rule.

required

Returns:

Type Description
SupportsRichComparison

Zero if the name starts and ends with two underscores, otherwise one.

Source code in src/pyorder/rig/order/module.py
def special_method_rank(
    self,
    definition: AnyDefinition,
    _definitions: tuple[AnyDefinition, ...],
) -> "SupportsRichComparison":
    """Rank dunder names before other definitions.

    Args:
        definition: Definition whose name determines the rank.
        _definitions: Other definitions; not used by this rule.

    Returns:
        Zero if the name starts and ends with two underscores, otherwise one.
    """
    name = definition.name
    if name.startswith("__") and name.endswith("__"):
        return 0
    return 1
standard_definition_ranks
standard_definition_ranks() -> tuple[
    Callable[
        [AnyDefinition, tuple[AnyDefinition, ...]],
        SupportsRichComparison,
    ],
    ...,
]

Return the final tie-breaking policies shared by all scopes.

Returns:

Type Description
tuple[Callable[[AnyDefinition, tuple[AnyDefinition, ...]], SupportsRichComparison], ...]

The visibility rank followed by the name rank.

Source code in src/pyorder/rig/order/module.py
def standard_definition_ranks(
    self,
) -> tuple[
    Callable[[AnyDefinition, tuple[AnyDefinition, ...]], "SupportsRichComparison"],
    ...,
]:
    """Return the final tie-breaking policies shared by all scopes.

    Returns:
        The visibility rank followed by the name rank.
    """
    return (
        self.definition_visibility_rank,
        self.definition_name_rank,
    )
write_text
write_text(file: Path, code: str) -> None

Overwrite a file using its detected encoding and newline sequence.

If no line terminator is detected, use LF.

Parameters:

Name Type Description Default
file Path

Path to an existing Python source file.

required
code str

Replacement contents with LF-normalized line endings.

required
Source code in src/pyorder/rig/order/module.py
def write_text(self, file: Path, code: str) -> None:
    """Overwrite a file using its detected encoding and newline sequence.

    If no line terminator is detected, use LF.

    Args:
        file: Path to an existing Python source file.
        code: Replacement contents with LF-normalized line endings.
    """
    encoding, newline = self.file_info(file)
    file.write_text(code, encoding=encoding, newline=newline)