Skip to content

References

funcsort.references

Load-time name analysis: what a statement binds, and what it reads while executing.

This module is the second libcst adapter (alongside :mod:funcsort.sorter); the pure constraint model it feeds lives in :mod:funcsort.ordering.

Reordering statements is only safe if every name a statement reads at the moment it executes is already bound. Decorator expressions, parameter defaults and assignment right-hand sides run immediately; function bodies do not. That distinction is the whole job of this module: it separates eager references (which constrain ordering) from lazy ones (which never do, or mutual recursion would freeze every block).

The governing invariant:

Over-collecting ``provides`` or ``requires`` is safe -- it only costs sorting.
Under-collecting ``requires`` emits broken code.

Every ambiguity below is therefore resolved toward over-collection.

_FUTURE_MODULE module-attribute

_FUTURE_MODULE = '__future__'

_ANNOTATIONS_FEATURE module-attribute

_ANNOTATIONS_FEATURE = 'annotations'

EMPTY_FLOW module-attribute

EMPTY_FLOW = NameFlow()

NameFlow dataclass

NameFlow(provides=frozenset(), requires=frozenset())

Names a statement binds, and the names it reads when it executes.

Attributes:

Name Type Description
provides frozenset[str]

Names bound in the enclosing scope by this statement.

requires frozenset[str]

Free names read eagerly, i.e. while the statement itself runs.

provides class-attribute instance-attribute

provides = frozenset()

requires class-attribute instance-attribute

requires = frozenset()

merge

merge(other)

Return the union of two flows (used for multi-statement lines and blocks).

_BoundNames

_BoundNames()

Bases: cst.CSTVisitor

Collect the names a statement binds in its enclosing scope.

Descends through compound statements (an if TYPE_CHECKING: block really does bind its imports at module level) but never into a function body, whose bindings are local.

Start with an empty binding set.

names instance-attribute

names = set()

visit_FunctionDef

visit_FunctionDef(node)

Bind the function name; its body binds only locals.

visit_ClassDef

visit_ClassDef(node)

Bind the class name; its body binds class attributes, not enclosing names.

visit_Lambda

visit_Lambda(node)

Skip a lambda: it binds nothing in the enclosing scope.

visit_AssignTarget

visit_AssignTarget(node)

Bind every name reachable through a (possibly destructuring) assignment target.

visit_AnnAssign

visit_AnnAssign(node)

Bind an annotated target only when it actually has a value.

A bare x: int is a declaration; at runtime it binds nothing, and pretending otherwise would create a spurious second provider for x.

visit_AugAssign

visit_AugAssign(node)

Bind the target of an augmented assignment, which rebinds it.

visit_NamedExpr

visit_NamedExpr(node)

Bind a walrus target, which lands in the enclosing scope.

visit_Import

visit_Import(node)

import a.b binds a; import a.b as c binds c.

visit_ImportFrom

visit_ImportFrom(node)

from x import y as z binds z; import * is treated as binding nothing.

visit_For

visit_For(node)

Bind the loop target, which lands in the enclosing scope.

visit_AsName

visit_AsName(node)

with ... as x and except ... as e bind their names.

visit_ExceptHandler

visit_ExceptHandler(node)

Bind the exception alias, then continue into the handler body.

visit_MatchAs

visit_MatchAs(node)

Bind the name captured by a match pattern.

visit_MatchStar

visit_MatchStar(node)

Bind the name captured by a starred match pattern.

visit_TypeAlias

visit_TypeAlias(node)

type X = ... binds X; the value is lazily evaluated (PEP 695).

_bind_target

_bind_target(target)

Bind every Name reachable through a destructuring target.

_FreeNames

_FreeNames(*, lazy_annotations)

Bases: cst.CSTVisitor

Collect the names a statement reads eagerly.

Two failure modes matter, and they are not symmetric. Missing a reference emits code that raises NameError; inventing one merely blocks a reorder. So the visitor defaults to recursing, and only carves out cases that are provably not references (attribute labels, keyword argument names, parameter names) or provably deferred (function and lambda bodies, string annotations).

Start with an empty reference set.

lazy_annotations instance-attribute

lazy_annotations = lazy_annotations

names instance-attribute

names = set()

visit_Name

visit_Name(node)

Record a bare name reference.

visit_Attribute

visit_Attribute(node)

a.b.c references only a; b and c are attribute labels.

visit_Arg

visit_Arg(node)

f(x=1) references f and 1, never the keyword x.

visit_Param

visit_Param(node)

Read only a parameter's default and annotation; its name is a binding.

visit_FunctionDef

visit_FunctionDef(node)

Read the signature eagerly; the body runs later and constrains nothing.

Decorators are visited as whole expressions -- @given(_class_source()) depends on _class_source, which a name-only reading of the decorator misses.

visit_ClassDef

visit_ClassDef(node)

Recurse into a class body, which executes at definition time.

Names bound inside the body are deliberately not subtracted: name = name idioms make subtraction unsound, and keeping them only adds a harmless edge.

visit_Lambda

visit_Lambda(node)

Lambda defaults are evaluated now; the body is not.

visit_Annotation

visit_Annotation(node)

Dispatch through the shared annotation rule.

visit_AssignTarget

visit_AssignTarget(node)

Read only what a target dereferences: obj.attr and d[k] need their base.

visit_AnnAssign

visit_AnnAssign(node)

Read the annotation and the value; the target is written.

visit_AugAssign

visit_AugAssign(node)

x += v genuinely reads x as well as rebinding it.

visit_Import

visit_Import(node)

Skip an import: it reads nothing from the enclosing scope.

visit_ImportFrom

visit_ImportFrom(node)

Skip an import: it reads nothing from the enclosing scope.

visit_TypeAlias

visit_TypeAlias(node)

PEP 695 alias values are lazily evaluated, so they constrain nothing.

_visit_target

_visit_target(target)

Read only what an assignment target dereferences.

x = v reads nothing from x, but obj.attr = v must read obj and d[k] = v must read both d and k -- those objects have to exist already.

_visit_annotation

_visit_annotation(annotation)

Recurse into an annotation unless it is deferred.

A string annotation is never evaluated. Non-string annotations are evaluated at definition time unless the module opted into PEP 563. PEP 649 (3.14) makes them lazy unconditionally, but funcsort cannot know the target interpreter of the file it formats, so the eager reading stays -- it is the safe over-collection.

name_flow

name_flow(node, *, lazy_annotations=False)

Return the :class:NameFlow of a single block-level statement.

Parameters:

Name Type Description Default
node cst.CSTNode

A statement from a module or class body.

required
lazy_annotations bool

Whether annotations are deferred (from __future__ import annotations), in which case they contribute no eager references.

False

Returns:

Type Description
NameFlow

The names the statement binds and the names it needs at execution time.

uses_future_annotations

uses_future_annotations(module)

Return whether the module defers annotation evaluation via a __future__ import.

_dotted_name

_dotted_name(node)

Normalise an attribute/name chain to its dotted form, or "" for anything else.

_root_name

_root_name(node)

Return the leftmost component of an attribute chain (import a.b binds a).

_alias_name

_alias_name(alias)

Return an import alias's as name, or "" when it has none.

_bound_names

_bound_names(node)

Return the names node binds in its enclosing scope.

_free_names

_free_names(node, *, lazy_annotations)

Return the names node reads while it executes.