Safety and limitations¶
The fixer's job is to change code without changing behaviour. Everything on this page follows from one rule: when a rewrite cannot be proven safe, the file is left exactly as its author wrote it and the reason is reported.
All-or-nothing, per file¶
A file is rewritten completely or not at all. Before anything is written, the fixer plans every rename in the file and runs every guard over it; if a single guard fires anywhere in that file, the whole plan is discarded and the original source is returned untouched. There is no partial rewrite, and no state in which some references were qualified and others were not.
Each declined file is explained by one or more CP003 findings pointing at
the line responsible.
What the rewrite is built on¶
Renames come from libCST's scope analysis, not from text matching. That means a rename applies only to accesses whose referents resolve uniquely to the import binding being rewritten. Concretely:
- a local variable in some function that happens to share the name is left alone;
asaliases are followed —from a.b import C as Drewrites uses ofD;- a dotted access
obj.Cis not a reference to the importedCand is not touched; - imports inside function and class bodies are fixed too, each scope getting its own binding, tracked independently of any module-level import of the same module.
A module the file already imports is reused as the binding — import json
plus from json import dumps becomes json.dumps — but only when that import
is certain to have run by the time each rewritten read does: it sits directly
in the body of its module or function (not under an if, try, with,
loop or match; if not TYPE_CHECKING: counts as direct, since it always
runs) and ends textually before every one of those reads. Otherwise the line
gets its own import, aliased (json_2) if the name is taken. The same holds
for a binding one rewritten line creates and a later one would share — with
one more safe case: two lines in the same block (the same if body, say)
share it, since the second only runs after the first.
Formatting survives because libCST is a concrete syntax tree: it round-trips the source, so what the fixer does not deliberately change is reproduced byte-for-byte. The structural changes are the inserted or replaced import statement and the qualified references. The original import line's leading blank lines and comments are carried onto the first replacement line, and its trailing comment onto the last.
Comments are never altered, and they are never silently dropped: in the cases where a rewrite could not carry a comment across, the file is declined instead. Those cases are listed below.
The same holds for bytes: a file is read and written in its own encoding, BOM
and line endings (see Encodings and line endings),
and --fix replaces it atomically, so an interrupted run never leaves a
truncated source file behind.
When a file is skipped¶
Any one of these blocks the entire file. Each emits a CP003 finding naming
the line.
A reference to the local name inside a string literal¶
__all__ = ["Widget"], getattr(mod, "Widget"),
monkeypatch.setattr("pkg.mod.Widget", ...) — these keep working only if the
spelling of the name survives, and a rename would silently break them. So a
string literal that could be referring to a rewritten name blocks the file.
This guard fires on the set of names actually being rewritten, so a name kept
for another reason never reaches it. The plain __all__ re-export is the
common case: if nothing in the module reads Widget, the
never-read rule keeps the import first and the file is
left alone without this guard being consulted at all. The example above is the
one where the module both re-exports Widget and uses it.
Two conditions must both hold. First, the name has to appear in the string as
a whole word — a substring match is not enough, so Widget does not match
inside WidgetFactory. Second, the string has to be code rather than
prose.
That second condition matters because most word matches in real code are
prose that no rename can reach: "expected Type, got int",
"--include=PATTERN", "@pytest.yield_fixture is deprecated". A string can
only reach a binding by being a reference to it — an __all__ entry, a
getattr argument, an eagerly evaluated annotation, an eval/exec
payload, an importlib or entry-point address. Every one of those is either
valid Python or a dotted/colon path; prose is neither.
So the string's content is parsed, and it blocks when the name turns up as a genuine reference in the result:
- a
Nameor the.attrof an attribute access, so both halves of"pkg.mod.Widget"count — the leaf of a dotted path is exactly whatmonkeypatch.setattrtakes; - a keyword-argument name, or an
import/from ... importalias, because a string carrying code that names the symbol is a template or anexecpayload rather than prose. Neither is a reference a rename would really break; they are included because over-blocking costs a declined file and the other direction costs broken code; - a string nested inside the parse, recursively —
"Sequence['Widget']"is a forward reference in its own right, and the inner'Widget'has no syntax node of its own to be visited separately; - a
>>>anywhere in the content, which is a doctest and therefore executable, whatever else the string contains.
A string whose content is not text at all — a bytes literal whose raw source spells the name — cannot be parsed and so cannot be cleared either. It is reported and blocks, like anything else the tool cannot classify.
This deliberately over-blocks in one direction: a string that happens to
parse as Python without being a reference still blocks. "Widget-case"
parses as the subtraction Widget - case, and "{Widget}" parses as a set
literal, so both block even though a .format() field name and a
parametrize id are inert. Clearing those would mean deciding by intent
rather than by structure, which is the guess this guard exists to avoid.
Two exceptions:
-
Genuine prose docstrings are exempt. A docstring is identified structurally — the value of an expression statement that is the first statement of a module, class or function body — never guessed at from position or content. A string anywhere else (a pseudo attribute-docstring after an assignment, a string inside a list,
__all__) is not a docstring and keeps blocking. The reasoning: a docstring naming an imported symbol is extremely common, it is describing the import rather than depending on its exact spelling, and a stale name in prose is a documentation nit rather than broken code. Treating it as unfixable would block a rewrite on a large fraction of real files.A doctest is different.
>>> Thing()is executable and a rename genuinely breaks it, so a docstring containing>>>anywhere is not exempt and blocks like any other string. -
Lazy string annotations are rewritten, not blocked. Under
from __future__ import annotationsan annotation is never evaluated at runtime, so a string sitting in a genuine annotation slot is rewritten along with the code rather than treated as a mention.This is done by parsing the string's contents as an expression and walking it structurally, not by substituting text.
Literal[...]arguments are values rather than type references, so that whole slice is skipped;Annotated[T, ...]mixes a real type with arbitrary metadata, so only the first element is descended into. If a candidate string cannot be parsed, or the rewritten result cannot be re-wrapped in its original quoting and round-tripped back exactly, it is not guessed at — it is left alone, and the ordinary string-mention guard then judges it. The same check catches content that carries trivia re-rendering would drop, such as a trailing comment inside the annotation string.A string sitting in an annotation slot is code by context, whether or not it parses, and the string guard is told so. An
__all__list gets the same treatment for the same reason: it is a list of names by declaration, so every string in one blocks however it is spelled — including__all__ = "Widget helper".split(), whose contents are not Python and which no amount of inspecting them could recognise. One level of indirection is followed, so__all__ = _EXPORTSalso covers whatever built_EXPORTS— one level, not a general dataflow analysis, which is as far as the idiom goes. That is what separates the two reasons a string can fail to parse."expected Type, got int"is prose and is cleared;"Widget["in an annotation slot is a malformed type — unclassifiable, not inert — and blocks. Nothing about the content alone distinguishes them, so the distinction is drawn where it is known: at the slot. Withoutfrom __future__ import annotationsthese strings are evaluated at runtime, sodef f(x: "list[Widget]")blocks there too.
f-strings
An f-string is not a blocking mention. Its interpolations are code, so
f"{Thing}" is rewritten to f"{mod.Thing}" like any other reference. A
plain string nested inside one — as in f"{getattr(m, 'Thing')}" — is
still an ordinary string literal, and still blocks.
The local name is rebound in the same scope¶
If the name bound by the import is also assigned somewhere else in the same scope, libCST's scopes are not flow-sensitive: an access lists both the import and the assignment as its referents, so there is no safe subset to rewrite. The file is declined.
A read the scope analysis does not tie to the import¶
Only the reads libCST links to the import are qualified, and it does not link
a read that comes before the import in the same scope: it looks for an
earlier binding, finds none, and falls back to the enclosing scope. In a loop
that is working code — for i in range(2): if i: out.append(dumps(1)) else:
from json import dumps — and the read left unqualified would raise
NameError once the import is gone. So every read of the name that could see
the import (in its scope, or a nested one that does not bind the name itself)
must be one libCST ties to it; any other declines the file.
A wildcard import in the file¶
from x import * binds whatever x exports, which may be the very name the
rewrite binds the module under — from json import dumps next to a star
import of a module exporting json would have json.dumps read that json
instead. What a wildcard import brings in is not proven, so in a file with one
the fixer creates and reuses no module-level binding: a module-level rewrite
declines the file, and a rewrite inside a function binds its own import there.
global / nonlocal declarations naming it¶
Such a declaration keeps the name writable from another scope. Qualifying the reads without also rewriting the writes would silently decouple them.
A del of the local name¶
libCST records del x as a read of x, so it sails past the rebinding
check and would be rewritten to del mod.x — which does not unbind a local at
all. It deletes the attribute from the imported module in sys.modules,
breaking every other importer of that module. del name right after an
import is a real __init__.py cleanup idiom, so this is not theoretical.
A match capture pattern binding the local name¶
case Name: is a capture pattern: it always matches and binds Name.
Rewriting it to case mod.Name: turns it into a value pattern, which matches
only when the subject equals mod.Name — a silent change of control flow.
libCST reports the captured name as an access of the import, so nothing else
in the fixer can tell the two apart. The case [*rest] and case {**rest}
binding forms are covered by the same rule.
case Thing(): (a class pattern) and case mod.Thing: (already a value
pattern) are genuine references and are rewritten normally.
An import under if TYPE_CHECKING: without future annotations¶
Moving such an import changes what name is bound, and with eagerly evaluated
annotations that raises NameError at runtime. So a TYPE_CHECKING-gated
import is only rewritten when the file has from __future__ import
annotations active — and then both the import and any lazy string annotation
mentioning the name are rewritten together.
A comment inside the import statement¶
The kept-names line is regenerated from text, which cannot carry a statement's
interior trivia across. A comment inside a parenthesized multi-line import —
including a per-name # noqa: or # type: ignore — would therefore vanish.
Rather than discard it, the file is declined.
Removing the import line would discard its comment¶
When the module is already bound elsewhere and nothing on the line needs to be kept, the import line disappears entirely, leaving nowhere to put a leading or trailing comment attached to it. Discarding an author's comment silently is worse than declining the fix, so the file is left alone. A blank line before the import is not a comment and does not block.
The rewrite would move a suppression comment¶
An inline suppression covers the imports on its physical line. A partial rewrite writes the kept names on one line with the statement's trailing comment, so a comment that covered only a rewritten name, or none, could end up covering — and suppressing — the kept ones. The coverage of every suppression is recomputed on the output, counting each import separately (the same name imported twice is two imports), and any comment whose coverage changes — other than losing the names the rewrite takes away — declines the file.
A configured alias is taken in the scope¶
When an alias rule applies to the module a
rewrite would bind, the new binding must have the configured name (or, for
as = false, the module's own leaf). If that name is already taken where the
binding would go — the same set of names that makes an unconfigured rewrite
fall back to helpers_2, which includes a builtin read there, so from
demo.list import go with list(go()) becomes from demo import list as
list_2 — no other name will do: a suffixed one breaks the
convention, and --fix never introduces a CP006. The file is declined, with
a CP003 naming the alias, the module and the rule. The same happens when a
{leaf} template renders a name no import can bind (a keyword, or
__debug__) for the module being bound.
Renaming a binding (CP006)¶
--fix renames a binding the alias check reports as CP006 — and only
those: one a suppression or a skip rule turned into a CP004, and every
module-level import of a package __init__.py, is left alone. The import
statement is edited in place (only the one alias of a multi-name statement
changes, and its comments stay where they are), and every access libCST
resolves to the binding is renamed, in nested functions, classes, lambdas and
comprehensions and f-strings, and in lazy string annotations under from
__future__ import annotations. Any one of these declines the whole file:
- The name is taken. The expected name is bound in the binding's scope, an enclosing function or class, or the module; bound by a scope between a renamed reference and the binding; or read, unbound, where the binding is visible (a builtin, say). The same set a new binding must avoid, and it includes a name another rename in the file has claimed.
- The old name is not one binding. It is assigned again in the same scope
(a rebinding, an augmented assignment, a
for,withorexcepttarget, a walrus, amatchcapture), deleted withdel, or declaredglobalornonlocalanywhere in the file; or a read of it could resolve to another binding too, or is not tied to the binding at all (a read above the import in its own scope, as in a loop — see above). - The file has a wildcard import and the binding is at module level: the star import could bind the new name (see above).
- Something may read it that the rename cannot reach. A string naming it
(
__all__,getattr(module, "npy"), a doctest, a string annotation that is not lazy or cannot be re-rendered) — the string guard above. For a module-level binding, also: nothing in the file reads it (so something outside may), another analysed file imports it, or a string elsewhere names its dotted path. A binding in a class body is a class attribute, read through the class or an instance where no scope analysis can see, and is always declined. - The statement cannot carry it.
import a.b.cwith noasbindsa, shared with every othera.*use; a binding underif TYPE_CHECKING:withoutfrom __future__ import annotations; dropping anasclause that holds a comment or a line break; or a{leaf}template that renders a name no import can bind.
A rename and a from-import rewrite are planned together: a rewritten
from numpy.linalg import norm reuses a module-level import numpy as npy
under the name it is renamed to (when that import is bound before the reads,
as for any reuse), and a new binding avoids every name a rename
claims. A function-local binding is not reused by a rewrite in the same
function, so a rewrite there that would bind the expected name declines the
file.
The file's encoding cannot hold the rewrite unchanged¶
The rewrite is written back in the encoding the file was read in. If the file
uses a legacy codec whose decoding does not round-trip — cp932, for one,
reads two different byte sequences as the same character — writing it back
would change lines the fix never touched, so the file is declined instead. The
same applies to a rewrite that would need a character the file's encoding
cannot represent — from . import C in pkg/анализ/mod.py becomes
from .. import анализ, naming the package after its directory, in a file
that may be declared latin-1 — and to a file libCST itself does not
reproduce byte for byte, such as one whose last line ends in a lone \r,
which libCST drops.
The rewrite did not re-parse¶
A final backstop rather than a guard: after rewriting, the result must parse.
If it does not, the original content is kept and an internal-error CP003 is
reported. cleanporter never hands back source it cannot compile.
What a skip rule can and cannot do¶
skip rules let you declare a region off-limits
for reasons the tool cannot discover — a body some framework re-parses, a
namespace some framework reads. What a rule guarantees:
A
skiprule never changes how a name is rewritten, and never causes a name to be rewritten that would not have been. Every line inside a skipped region is byte-identical in the output to what you wrote.
Nothing in a rule reaches the resolver: a skip never supplies a verdict, never turns "undetermined" into an answer, and never relaxes a guard. A skipped name joins the same keep list an explicit re-export is already on, so the all-or-nothing contract above is untouched.
It does not follow that a rule can only make --fix do less, and the
difference is worth knowing before you write one. Every whole-file guard is
keyed on the set of names being rewritten, so keeping a name takes its blocker
with it. A file that was declined entirely because __all__ names the one
symbol your rule now pins will have its other imports rewritten instead. That
is sound — the pinned name is still bound, and the guard still fires for every
name that is still being rewritten — but the file changes more, not less.
exempt_names has always worked this way; a rule is not special.
An inline suppression takes the same
path: the finding it names becomes a CP004, and the name joins the same
keep list, so everything above holds for it too.
One more edge, enforced rather than documented away: a rule can match code the
fixer is about to write. { decorator = 'gtx\.field_operator' } matches
nothing in a file that imports the decorator bare and writes @field_operator,
so the body is not skipped and gets rewritten — and the resulting
@gtx.field_operator is then a region your config declares off-limits, covering
code that was just edited. cleanporter recomputes the regions on its own output
and declines the file (CP003) rather than apply a rewrite its own
configuration would have forbidden. Prefer the bare last-component spelling
({ decorator = 'field_operator' }), which matches both.
Known limitations¶
-
An import nothing in the file reads is never rewritten.
from p import Thingwith no read ofThinganywhere in the file has no use site to qualify, so rewriting it would remove a violation while changing no call — and its one real effect would be to dropThingfrom this module's namespace.That namespace is not always private. A test module's
from .fixtures import backend_likeexists only so pytest can find the name by a test's parameter; aconftest.pyis nothing but such imports. Neither is visible to the re-export guard below, because the consumer is a function signature, not an import statement. So the import is kept and reportedCP003, and your options are the honest ones: delete it, or declare it with askiprule orexempt_names."Read" here means libCST's scope analysis, not a text match. A parameter named
backend_like, and every use of it in the body, belong to the parameter's binding and are not reads of the import.Because answering this needs scope metadata that only the fix path resolves, a plain
checkrun reports these as theCP001they are; it is--fixand--diffthat name themCP003. - A first-party object is one its parent binds, read by parsing. WhenP.NAMEis not on disk, it is called an object only if every binding ofNAMEinP's source resolves to one, eachfrom M import Xfollowed to its origin (see How it works); anything short of that isCP002. That turns some imports a looser rule would have calledCP001intoCP002— a generated_version, a_pb2, a name a PEP 562__getattr__could supply — which is the intended trade. What the parse does not see:- bindings made by running code rather than by a statement — a write
through
globals()orsys.modules, a__path__extended at import time; - a
del NAMEat module level, or aglobal NAMErebinding inside a function: the name still counts as bound by the statements that bind it; - statement order. A star import from a module this run cannot read
(third-party, or with an
__all__built at run time) leaves every name the parent could get from it undetermined, even one the parent also defines itself — the definition usually comes later and wins, but "usually" is not proof, and following order through conditional andtrybodies is a heuristic this layer deliberately does without. This is a known, accepted source ofCP002. - Relative imports stay relative, and one form is kept.
from .sub.mod import Cis rewritten tofrom .sub import modplusmod.C. The absolute name is what the resolver classifies, but it is only as good as the import root cleanporter inferred for the file, so it is never written out: a PEP 420 namespace directory once turnedfrom .readers import readintofrom io import readers(see Import roots). The relative replacement climbs from wherever the file really is, exactly as the original did.
from . import Chas no module part to split: it imports from the package itself, and a relative import can name a package only from its parent. Inpkg/sub/mod.pythat isfrom .. import subplussub.C. This spelling does depend on the root givingsuba parent package, but only in a way that fails loudly: if the root is wrong andsubis really top-level, the import raisesImportError("attempted relative import beyond top-level package") the first time the module is imported. It can never silently bind a different module the wayimport iodid. Like any replacement, it is also checked to bind the package it names (see below).When the package is top-level under this run's roots —
from . import __version__inpkg/cli.pyis the common case — there is no relative spelling at all, and the absolute one,import pkg, would depend on the import root where the original did not. That import is reportedCP003and kept exactly as written, in every mode; the rest of the file is still fixed.Unless the root is declared, and soundly so. When the file sits under a root you named with
--rootorsource_roots— and that root is the one the file is qualified against — the package's name is no longer a reading of the directory tree but what you said is onsys.path, soimport pkgbinds exactly the package the dots reached. There the import is an ordinaryCP001, incheckand--fixalike, and--fixwritesimport pkgpluspkg.C. A declaration is taken at its word only when it is not self-evidently wrong, so theCP003stays when:- the declared directory, or any directory above it up to the project
root, is a package (holds an
__init__.py):source_roots = ["src/pkg"], or["lib/vendor"]under alib/__init__.py, puts a package's inside onsys.path, whereimport utilscan reach some other top-levelutils. This is read from the disk, whatever paths the run is given; - it nests inside, or contains, another import root, declared or
inferred — the layout cleanporter already warns about ("import roots
nest"), where one file has two dotted names; a
tests/__init__.pybesidesrc/is enough; - another root holds a top-level
pkgas well, so which oneimport pkgfinds depends onsys.pathorder; - the file is
pkg/__init__.pyitself, whereimport pkgwould only bind the package to a name inside itself (this one has its own reason, since no declaration changes it); pkgis named like a standard-library module: this interpreter'ssys.stdlib_module_names, plus the top-level modules removed in 3.12 and 3.13 (imp,distutils,asyncore,cgi,telnetlib, …) and added in 3.14 (annotationlib,compression), since the target interpreter may be any supported version.import iois the standard library's whatever your root holds.
Under an inferred root that would pass those checks, the
CP003message names it — "if<root>is where Python imports it from, declaring it with--rootorsource_rootslets--fixwriteimport pkg". Declare it only if that is true: the declaration is the whole of the evidence. Some trust in it is irreducible — a PEP 420 namespace parent above the root leaves nothing on disk to show that the package is really imported under a longer name, so no check here can catch that declaration being wrong.A relative and an absolute import of the same module in one file are given separate module bindings (one of them aliased,
mod_2): they are the same module only if the inferred root is right. Two relative imports of one module share a binding however they are spelled, since both climb from the file's own package. - Imports are not re-sorted. The fixer inserts or replaces a statement in place rather than reflowing the import block. Use isort or Ruff separately for layout. - Wildcard imports are never rewritten.from x import *is reported asCP003— there is no module import that reproduces it — in every mode, including plain check mode. - Explicit re-exports are never rewritten.from .exceptions import UsageError as UsageErroraliases a name to itself, which does nothing at runtime and is therefore only ever written to declare that the name is part of this module's public surface. PEP 484 calls it a redundant alias; mypy'sno_implicit_reexportand ruff'sF401both read it that way, which makes it the one re-export marker that is machine-readable rather than guessed at.Rewriting it would delete a public name: that line is what makes
from pkg.config import UsageErrorwork in every other file, including files this tool may never be pointed at. It is the same failure the__all__string-mention guard catches, stated in syntax instead of in a string, so it gets the same answer — reported asCP003, in every mode, and left exactly as written. Like an unresolved name it is kept in place rather than blocking the whole file, so the file's other rewrites still happen. An ordinary alias (import Thing as T) carries no such declaration and is rewritten normally. - A load-bearing re-export is never rewritten. Ifpkg/tool.pysaysfrom pkg.display import dump, thenpkg.tool.dumpexists only because of howtool.pywrites that import — and this tool may be about to rewrite it, in the same run. Fixingtool.pyis correct on its own terms and deletespkg.tool.dump; rewriting another file'sfrom pkg.tool import dumpintotool.dumpis correct on its own terms and points at what that deletion removed. Both are right alone and wrong together.The re-exporting side is the one protected.
tool.py's own import is reportedCP003and left alone when two things hold:tool.pybinds the name by importing it rather than defining it, so a rewrite would remove the attribute at all; and some analysed file usespkg.tool.dump. A use is any of three shapes:from pkg.tool import dump;dumpread as an attribute of a module binding —import pkg.toolthenpkg.tool.dump, orfrom pkg import toolthentool.dump;from pkg.tool import *, which could need any of the module's re-exports, so all of them count.
The attribute shape is not an extra: it is the form this tool rewrites everything into. Counting only
fromimports made--fixnot convergent — the first run rewrote the consumer totool.dump, erasing the very evidence it had relied on, and a second run then deleted the attribute the first run had protected. A run with findings left exits non-zero, which is exactly what invites that second run, so this mattered.The consumer is then rewritten as usual — the attribute it qualifies through is guaranteed to survive.
A re-export nobody uses is free to fix. A name bound both ways (imported under a
try, defined in theexcept) survives a rewrite and is not affected. Third-party modules are never rewritten, so their re-exports do not move and are not considered: the hazard exists exactly where the fixer's reach does, and so does the guard.When more than one file on disk claims the same dotted name —
pkg.pyleft sitting besidepkg/, which is what an older single-file release looks like next to a newer packaged one, or the same package present under two import roots — every claimant is asked, and any one of them that re-exports the name protects it. Which file an interpreter actually imports is asys.pathquestion the filesystem does not settle, and getting it wrong is only expensive in one direction: consult the file that loses, hear "not a re-export", and the guard stands down while the rewrite deletes an attribute another file imports. The cost of the safe answer is a fix declined when the losing file was the one re-exporting.The evidence is the set of files under analysis, and it is evidence a parse can see. A consumer outside the run is the documented cross-file limitation. A consumer inside the run that reaches the name through a string —
getattr(tool, "dump"),sys.modules["pkg.tool"].dump— is not evidence either, for the same reason those strings are opaque to the string guard. Both make the re-export look unused, and it is then fixed — the same string-opacity family as the accepted limitations below. A string that spells the whole dotted path is different, and has a guard of its own: the next item. - A re-export named by a string in another file is never rewritten.monkeypatch.setattr("pkg.tool.dump", ...)in a test,mock.patchof the same,importlib.import_module("pkg.tool")beside a"pkg.tool:dump"plugin address, ordump = "pkg.tool:dump"under[project.scripts]: each keeps working only whilepkg/tool.pybindsdump. Rewriting its import leaves every one of them importing, parsing and type-checking — and then failing at runtime, or, for a patch, silently patching a name nothing reads any more. This is the load-bearing guard above with strings as the evidence, and it declines the same way: that one import is kept and reportedCP003, in every mode, naming the string and where it is ('pkg.tool.dump' is named by the string 'pkg.tool.dump' at tests/test_tool.py:12); the rest of the file is fixed.The evidence is every string literal in the run whose whole text is a dotted path of two or more identifiers (
a.b.c) or an entry-point spec (a.b:c,a.b:c.d). A literal is a plain string, an f-string with no placeholders, or an implicit concatenation of those ("pkg.tool." "dump"), read whole; bytes, escapes and placeholders are not paths. To that is added every string value of thepyproject.tomlin use, in any table and at any depth —[project.scripts]and[project.entry-points.*], but also[tool.poetry.scripts],[tool.poetry.plugins.*]or a tool's own plugin setting — read as an entry point where it is one (whitespace around the colon and an[extras]suffix are dropped, nothing else is) and as a dotted path otherwise. The reason gives the line that assigns that key the value in its own table — proved by re-parsing the file with that value swapped out, so a look-alike inside a multi-line string or under a fake header is never named — or the file alone when the value sits in an array, an inline table or a multi-line string. Every split of the path is a candidate —"pkg.tool.dump.__name__"namesdumpinpkg.toolas surely as"pkg.tool.dump"does — and a candidate counts only when its first component is first-party and the module re-exports the name, exactly as for the load-bearing guard. So a string naming another attribute of the module, one it defines itself, or something outside the project blocks nothing, and neither does prose ("see pkg.tool.dump") or code ("pkg.tool.dump()"): the cross-file reading is of paths only. It is collected from the same single walk of each file as everything else. In a--whole-projectrun it covers the whole tree, so a test file that was not listed still protects what it patches.A string in the file being rewritten is not this guard's business. Under
--fixthe string guard above sees it mention the name the rewrite would qualify and declines the whole file with aCP003; a plain check reports the import asCP001. Both are as they were before this guard. - A package's__init__.pykeeps its module-level imports. Everyfrom P import Sthere outside adeforclass— under a module-leveltry,iforwithtoo — binds an attribute of the package, and those attributes are its public surface:from ._version_info import VersionInfoin attrs'attr/__init__.pyisattr.VersionInfo. Nothing need read that name, list it in__all__, import it or spell it in a string, so none of the evidence-based guards here can see what the rewrite would delete. So the rule is structural rather than evidential: such an import is compliant (see A package's__init__.py), never reported and never rewritten, in every mode — the one decisioncheckand--fixshare makes it, so they cannot disagree. It is per import, not per file: an import inside a function in the same__init__.pybinds a local (in a class body, a class attribute) and is still fixed, and nothing else in the file is blocked. One aglobalstatement turns back into a package attribute is declined by theglobal/nonlocalguard above. - A module-level name inpkg/__init__.pyis the attributepkg.<name>, and that makes two things unsafe there that are fine anywhere else. Since the item above keeps every module-level import there as written, the fixer now only ever rewrites an__init__.pyimport inside adeforclass, whose binding is not a package attribute. Such an import can still reuse a module-level binding, though, so of the rules below the reuse half and the second rule are live; only the allocation half is now defence in depth.A new binding must not take the name of one of
pkg's own submodules. Rewritingfrom kombu.serialization import loadsinsidecelery/security/__init__.pytofrom kombu import serializationput kombu's module in the slot belonging tocelery.security.serialization— where it sits, unremarked, until the firstimport celery.security.serializationanywhere replaces the attribute and this file's ownserialization.loadsstarts resolving against the wrong module. So the alias allocator treats a sibling submodule's name as taken and picksserialization_2instead. Nothing is declined for this; it only changes which name is chosen. (No module-level import in an__init__.pyis rewritten any more, so this allocation rule no longer fires; it is kept as defence in depth.) Binding a submodule under its own name is the one case with nothing to collide — the global and the attribute would hold the same object — sofrom pkg import serializationinsidepkg/__init__.pyis still spelled without an alias.The same rule governs reuse, and this half is live. An import the author already wrote under a sibling submodule's name — a module-level
from kombu import serializationinpkg/__init__.py— is no more durable than one the fixer would allocate there, so a rewritten function-localfrom kombu.serialization import loadsnever qualifies references through it; a fresh alias (serialization_2) is bound in the function instead and their import is left untouched. Their binding was harmless while nothing depended on it, and qualifying through it is exactly what would have made it load-bearing.Second,
from pkg import Swritten insidepkg/__init__.pyis not a reliable way to reach the submodulepkg.S.from X import YimportsX, bindsgetattr(X, "Y"), and falls back to importing the submodule only when that attribute is absent — so any top-levelSalready bound in this file wins, silently. When that competing binding is the author's, aliasing cannot help: it has to stay. That import alone is reportedCP003and kept exactly as written, while the rest of the file is still fixed. - Every import the fixer would write has to be shown to bind the module it names. The rewrite offrom P.S import objisfrom P import S, and that statement bindsgetattr(P, "S")— so aP/__init__.pythat bindsSto something else hands the fixer's replacement that object instead, and everyS.objit wrote raisesAttributeError. The lazy re-export idiom (from .S import S, a function or class named after its own module) is exactly this shape; gt4py'siterator/transforms/concat_where/__init__.pyis the case that found it, andkombu/utils/__init__.pyis one the corpus had been rewriting into a latentAttributeErrorall along. Spelling the replacementimport P.S as aliaswould not avoid it: since Python 3.7 that statement resolves throughgetattr(P, "S")as well.Whether
P.Sis reachable is decided by the same rule the resolver uses forCP002— a name that is both a submodule on disk and a top-level binding in the package's__init__is ambiguous, never guessed — and it is asked of the import about to be written, not only of the one that was read. Both layers answer it, and both by looking at what__init__.pybinds: the filesystem one by parsing it, the interpreter probe by reading the name out of the imported package's__dict__— the attribute the__init__wrote, which is not quite the attribute the import would bind (see the limits below).Anything short of a firm "yes, a module" keeps that one import exactly as written and reports
CP003, while the rest of the file is still fixed.A
P.Sthis run cannot see at all never gets that far. The module map answers for any name whose top-level component is first-party, scanned subtree or not, so a run pointed at one distribution of a namespace package cannot see a sibling's modules. It does not call them objects — an object needs a binding in the parent's source, and absence is not one — so the import naming one isCP002and nothing is written for it. The cost is a fix that would have been correct; the finding says which evidence was missing ("neither on disk under this run's import roots nor bound in …"), and pointing cleanporter at the whole tree (for a few files, with--whole-project), or declaringsource_roots, resolves it.Written inside
pkg/__init__.pythis is the same check: there the package's attributes are the file's own module-level names, so the binding that competes with the submodule is one the reader can see in the file being rewritten. - A file is blocked outright, not partially fixed, whenever a rewritten name is referenced by a non-docstring string literal, appears inside a doctest, or when removing an import would discard its comment. See the section above. - Type comments are not inspected. A# type: ...comment naming a rewritten symbol is neither rewritten nor treated as a blocker. (A comment inside an import statement is a separate matter, and does block.) - SomeCP003findings can never be cleared by--fix. A wildcard import, an explicitS as Sre-export, a load-bearing re-export, a re-export another file names by its dotted path, a replacement that cannot be shown to bind the module it names, andfrom . import Cwhere the package is top-level under an inferred root (a sound declared root lifts it; see above) are all reported in every mode and are never rewritten, and the exit code countsCP003toward failure. A project that legitimately uses those idioms therefore cannot reach exit0on the strength of--fixalone; the finding is a true statement about the code, not a defect to be fixed. Silence them withexempt_names,exempt_modulesorexcludeif you want a green run — cleanporter's own__init__.pydeliberately does not, and the README explains why. - A string the parse cannot see through is treated as prose. The string guard clears a string that does not parse as Python and is not a dotted/colon path. Content that is code is parsed both as written andtextwrap.dedent-ed, so an indentedexecblock still blocks. What slips through is content that no parse can reach: a regex literal matching the name at runtime (re.compile(r"\bWidget\b")applied to an attribute name), a payload assembled rather than written out (eval("Wid" + "get")), a fragment that is not valid Python on its own ("{indent}Widget()"fed through.format()), and source for a different Python version. The annotation-slot and__all__cases are not in this list: those strings are known to be code by context and keep blocking however they are spelled. - Some references from elsewhere are still invisible. A string in another file that spells a rewritten binding's dotted path out whole —monkeypatch.setattr("pkg.cli.helper", ...),mock.patch, an entry point inpyproject.toml— is guarded (see above). What is not: a dynamic string (f"{pkg}.cli.helper","pkg.cli." + name), a lookup of the name through a module object —getattr(module, "helper"),monkeypatch.setattr(module, "helper", ...),mock.patch.object(module, "helper"),sys.modules[...]— since the string there is the bare name, not a path, a reference in a file outside the run (another project, or — without--whole-project— a file that was not listed), and an entry point or dotted path in a config file other thanpyproject.toml(setup.cfg,tox.ini,pytest.ini, YAML). Any of those can go stale even though the rewritten file itself is correct. The unguarded case was found by running cleanporter over its own source: one test patchedcleanporter.cli.fix_record, a name the compliant rewrite no longer bound there. Re-run your test suite after a--fixsweep;--fixprints a note to stderr saying so whenever it writes a file. - One-liner suites and semicolon-joined imports get noCP003. They are reported asCP001and not rewritten, but no note explains that the fixer declined them. The fixer never plans such a line at all, and turning that into a blocker would make the whole file unfixable — strictly worse, since it would also stop the unrelated, provably safe rewrites in it. The violation is still reported; only the "declined, because…" note is missing. - All diffs go to one stream. Every changed file's patch is concatenated to stdout rather than written as a separate patch file. Headers are relative to the current directory, so the stream isgit apply-able as one patch. -six.movesis not exempt by default, even though the style guide mentions it. Add it with--exempt six.movesorexempt_modules = ["six.moves"]. - Probe results are not persisted. They are cached in memory for the run only, so a very large third-party surface re-pays the (batched) probe cost on every invocation. - A shadow supplied lazily, by a module-level__getattr__, is not detected. The probe reads the parent package's__dict__, which holds what its__init__bound eagerly; askinggetattrinstead would run the package's own code, import the leaf for every name it is asked about — the one thing the classifier promises never to do — and can raise, sincelazy_loader.attachis written to fail for a leaf whose optional dependency is absent. So a package that lazily supplies a non-module under a name that is also a submodule on disk is classified as a module, and the fix for its consumers is emitted. The self-referential lazy shape (the lazy import ofP.Sitself) is safe: it installs the real module in the slot before the import reads it. -__init__.pybindings are cached by path (and package) for the run, without an mtime check. This is safe only because nothing in a single run rewrites a scanned__init__.py's plain assignments — an assumption about the fixer's current narrow scope, not an enforced invariant. - Capture-pattern bindings in an__init__.pyare not collected when looking for names that shadow a submodule. A module-levelmatchstatement in an__init__.pybinding a name that collides with a real submodule is vanishingly rare; the limit is stated rather than silently assumed. - bindings made by running code rather than by a statement — a write
through