Skip to content

Sorter

funcsort.sorter

Core sorting logic for class methods and module-level functions.

The transformer is a thin libcst adapter over the pure model in :mod:funcsort.groups. A single shared helper (:func:sort_block) reorders the members of any block — a class body or the module body — so class and module scope share one implementation.

Ordering is not purely a grouping question. A statement that reads a name while it executes — a decorator expression, a parameter default — must stay after whatever binds that name, or the sorted file raises NameError on import. :mod:funcsort.references extracts those load-time dependencies and :mod:funcsort.ordering fits the preferred order to them.

_DEFAULT_METHOD_TYPE_ORDER module-attribute

_DEFAULT_METHOD_TYPE_ORDER = [MethodKind.INSTANCE, MethodKind.CLASS, MethodKind.STATIC]

_MAX_ORDERING_PASSES module-attribute

_MAX_ORDERING_PASSES = 8

_NOSORT module-attribute

_NOSORT = 'nosort'

_Placed module-attribute

_Placed = tuple[int, int]

BlockSortResult dataclass

BlockSortResult(new_body, modified, unmatched, outcome=OrderingOutcome.UNCONSTRAINED)

Outcome of sorting a single block (class or module body).

new_body instance-attribute

new_body

modified instance-attribute

modified

unmatched instance-attribute

unmatched

outcome class-attribute instance-attribute

SortResult dataclass

SortResult(path, modified, unmatched=())

Outcome of sorting a whole file.

path instance-attribute

path

modified instance-attribute

modified

unmatched class-attribute instance-attribute

unmatched = ()

_BlockPlan dataclass

_BlockPlan(
    members,
    bucket_keys,
    unmatched,
    problem,
    groups,
    method_type_order,
    classes,
    class_prerequisites,
    function_placement,
)

Everything about a block that stays constant however its candidates are permuted.

Splitting this out is what makes iterating to a fixed point cheap: the libcst work (classification and name-flow extraction) happens once, and only the pure bucketing and constraint solving repeat.

members instance-attribute

members

Candidate body index to its classified member.

bucket_keys instance-attribute

bucket_keys

Candidate body index to its bucket; candidates that matched no group are absent.

unmatched instance-attribute

unmatched

problem instance-attribute

problem

groups instance-attribute

groups

Ordered groups, giving the bucket emission order.

method_type_order instance-attribute

method_type_order

Secondary ordering, already expanded to cover every kind.

classes instance-attribute

classes

Candidate body indices that are classes, moved as one block by the placement.

class_prerequisites instance-attribute

class_prerequisites

Non-class candidates the classes read at load time, directly or transitively.

function_placement instance-attribute

function_placement

identity property

identity

Return the candidates in their original order (always a safe ordering).

step

step(order)

Bucket-sort order, then fit the result to the dependency constraints.

_desired

_desired(order)

Return the order the groups and the function placement want.

_grouped

_grouped(order)

Return the members in group order, given where they currently sit.

MethodSorter

MethodSorter(
    groups,
    method_type_order,
    *,
    sort_module=True,
    respect_dependencies=True,
    function_placement=FunctionPlacement.AFTER_CLASSES,
)

Bases: cst.CSTTransformer

Transformer that sorts class methods and (optionally) module-level functions.

Initialise the transformer with resolved configuration.

groups instance-attribute

groups = groups

method_type_order instance-attribute

method_type_order = method_type_order

sort_module instance-attribute

sort_module = sort_module

respect_dependencies instance-attribute

respect_dependencies = respect_dependencies

function_placement instance-attribute

function_placement = function_placement

lazy_annotations instance-attribute

lazy_annotations = False

modified instance-attribute

modified = False

blocked instance-attribute

blocked = False

unmatched instance-attribute

unmatched = []

visit_Module

visit_Module(node)

Record whether the module defers annotations, before any body is visited.

This has to be a visit_ hook: leave_ClassDef fires before leave_Module, so reading the future import on the way out would be too late for class bodies.

leave_ClassDef

leave_ClassDef(original_node, updated_node)

Sort the methods within a class definition.

leave_Module

leave_Module(original_node, updated_node)

Sort the top-level functions of a module when enabled.

_apply

_apply(body, scope)

Run the shared sorter on a block; record state; return the new body or None.

has_nosort_comment

has_nosort_comment(node)

Return whether node carries a # nosort directive.

Looks at leading comment lines, a trailing comment on the same line (assignments), and the trailing comment of a block header (functions/classes). Case-insensitive.

file_has_nosort

file_has_nosort(module)

Return whether the file has a # nosort: file directive in its header.

get_method_type

get_method_type(method)

Determine a function's binding from its decorators.

sort_block

sort_block(
    body,
    *,
    scope,
    groups,
    method_type_order,
    respect_dependencies=True,
    lazy_annotations=False,
    function_placement=FunctionPlacement.AFTER_CLASSES,
)

Reorder the sortable members of a block, anchoring everything else in place.

Disabling respect_dependencies restores pure group ordering, which can emit a file that no longer imports. lazy_annotations records that the module defers annotations (PEP 563), in which case annotation references impose no ordering at all. function_placement decides, at module scope, whether classes move so the functions stay together on one side of them.

sort_file

sort_file(
    file_path,
    groups=None,
    method_type_order=None,
    *,
    sort_module=True,
    check_only=False,
    show_diff=False,
    respect_dependencies=True,
    function_placement=FunctionPlacement.AFTER_CLASSES,
)

Sort the methods (and optionally module functions) of a Python file.

Omitting groups or method_type_order falls back to the built-in defaults. Under check_only nothing is written back to disk. Disabling respect_dependencies can produce a file that no longer imports. function_placement positions module-level functions relative to classes.

_plan_block

_plan_block(
    items,
    *,
    scope,
    groups,
    method_type_order,
    respect_dependencies,
    lazy_annotations,
    function_placement,
)

Classify a block into candidates and anchors, or return None if nothing can move.

_prerequisites

_prerequisites(targets, candidates)

Return the candidates, other than targets, that targets need bound first.

_is_movable

_is_movable(member, item, *, assignments_sortable)

Return whether a classified member may be reordered rather than pinned in place.

_bucket_key

_bucket_key(member, groups)

Return the member's (group name, method type) bucket, or None if it matched none.

_converge

_converge(plan)

Iterate bucketing and constraint solving until the order sorts to itself.

A returned fixed point makes a second funcsort run a no-op: re-sorting starts from that same order and immediately reproduces it. If the block cannot be ordered safely, or oscillates instead of settling, the original order is returned — always safe, because the file being sorted already runs.

_emit

_emit(items, plan, order, outcome)

Pour the ordered candidates back into their slots, leaving anchors untouched.

_decorator_names

_decorator_names(method)

Return the normalised dotted names of a function's decorators (calls stripped).

_decorator_name

_decorator_name(node)

Normalise a decorator expression to its dotted name (a.b.c), stripping calls.

_assignment_target_name

_assignment_target_name(line)

Return the single simple target name of an assignment line, else None.

_as_member

_as_member(index, node, scope)

Build a :class:Member for a sortable statement, or None for structural items.

_effective_method_type_order

_effective_method_type_order(method_type_order)

Return the order with any missing method types appended (never drop members).

_order_bucket

_order_bucket(bucket, current_position)

Order one bucket, minimising movement relative to the candidate sequence.

Members that started before the bucket's span (or before what is already placed) go first, members within the span keep their place, and members after the span go last — each subgroup stable by original position.