Repository navigation
Major release: scores follow more of the cognitive complexity paper. Comprehensions, loop and try else, mixed boolean operators, nested definitions, the decorator exception, recursion cycles, and conditional expressions anywhere in an expression are now scored as the paper prescribes. On the django source tree, 1,946 of 30,813 functions change score: 1,481 go down and 465 go up, and the total drops by 7%. The release also adds editor quick fixes, workspace-wide diagnostics, --fix for C005, --explain, rule groups, --force-exclude, and --output -. --plain lines now carry the line number, and every warning goes to stderr. Re-run complexipy after upgrading, review your thresholds and snapshots, and check the migration guide.
Added
--diff,--diff-only, and--stagedlist, below the diff table, each function that an ignore comment hides now but did not hide at the reference, aspath:line function score, the score taken with the comment disregarded. The list never changes the exit code, and--quiethides it. (#327)- Each JSON entry carries
line_start,line_end, andline_complexities: the lines that add to the score, one entry per line in line order, whosecomplexityvalues sum to the function'scomplexity. Two functions with one name in one file are now told apart by their lines. CSV, GitLab, and SARIF output do not change. (#325) --output -writes the report to stdout when exactly one--output-formatis selected, socomplexipy . --output-format json --output - | jq .works. stdout then holds only the report: the console output is suppressed as with--quiet, and warnings and errors go to stderr. The exit code is the same as with a file. With two or more formats,--output -fails before the analysis runs. (#324)- The language server answers
textDocument/codeActionwith one code action per refactoring suggestion of each function over the threshold in the requested range. A suggestion--fixwould apply is a quick fix that rewrites the buffer in one edit built by the same fix engine; any other suggestion is a disabled refactor action with its help text as the reason, and never edits. Each title states the reduction, or says it is not measured. The threshold diagnostic now links to its documentation throughcodeDescription. (#254) --select,--ignore, and theselectandignoreconfiguration keys accept a rule group:complexityorreadability. A group stands for every refactoring rule of that category, and mixes with rule ids, as in--select complexity,C007. A group name prints no unknown-rule warning. (#205)- The language server publishes diagnostics for files that are not open when
[lsp] workspace-diagnostics = true. It scans each workspace folder with the same file discovery and exclusion ascomplexipy, and refreshes a file when it is closed or changes on disk. The setting is off by default. A client that supports dynamic file watching now also reports.pychanges to the server, which ignores them while the setting is off. (#256) --explain <rule>prints a refactoring rule's id, name, category, applicability, description, and documentation link, and exits without running an analysis. An unknown rule id exits with an error that lists the valid ids. (#207)--fixapplies C005 (extract predicate). It inserts the helper above the module-leveldeforclassthat holds the function and rewrites the condition into a call. It does so only when every name the condition reads is sure to be bound; other conditions keep the snippet for hand application. C005 reduction is measured when the fix applies.CodeSuggestiongainsinsertions, a list of the newCodeInsertiontype, and the JSON output gains theinsertionskey. (#263)--force-exclude, alsoforce-exclude = truein the configuration, appliesexcludepatterns to files passed explicitly as arguments. Without it, an explicit file is analyzed as before. Pass it under pre-commit, which names each changed file, so the configuredexcludeapplies there. (#293)- The configuration schema is in the SchemaStore catalog, so a TOML language server such as Taplo completes and validates
complexipy.toml,.complexipy.toml, and[tool.complexipy]inpyproject.tomlwith no#:schemaline. (#270)
Changed (scoring)
- Comprehension
forandifclauses add nothing and no longer raise the nesting level, since a comprehension is shorthand for a loop.elseonfor,while, andtryadds +1 with no nesting increment, and its body raises the nesting level, likeelseafterif: the paper's hybrid increment. Mixed boolean operators are read left to right, soa or b and c or dscores 3 instead of 2. Scores drop for code with comprehensions and rise for loop andtryelse. Some mixed conditions score higher and some lower:(a or (b and c)) and dgoes from 3 to 2. (#342, #351) - Each function in a recursion cycle adds +1: indirect cycles (
acallsb,bcallsa), methods that callself.m()orcls.m(), and nested functions, whose +1 goes to the enclosing function, as the paper prescribes. Calls resolve within one file, by the rules in Understanding Complexity Scores. A method that calls a bare name equal to its own, such asdef get(self): return get(x), no longer scores as recursive. (#340) - A call through the class name, such as
K.s()in a static method ofK, now counts toward a recursion cycle whenKnames exactly one class of the file and no other binding ofKcan replace it. (#354, #363) - A bare-name call no longer counts as recursion when another binding hides the function, such as a parameter, an assignment, or an import, so
def f(f): return f()scores 0. When a scope binds the name both bydefand another way, the call counts only if the other binding always runs first:f = 1beforedef fkeeps the +1, andf = wrap(f)after it removes it. (#361) - A recursive call inside a lambda, or in the decorators, default arguments, bases, or class body of a definition nested in a function, now counts for the enclosing function. Lambda parameters, comprehension variables, and type parameters hide outer names, so
lambda f: f()insidefis not recursive. (#349) - A nested function raises the nesting level of its body wherever it sits, under
if,for,while,with,try,match, or in a class, as the paper prescribes. Before, only adefplaced directly in a function body did. A class body inside a function is now scored in full, and a class does not raise the nesting level itself. With--check-script, the body of a module-level class counts toward<module>; method bodies do not. (#339) - The Python decorator exception applies only when a function returns its nested function, by name or as a direct argument of a call such as
functools.wraps(f)(inner), soreturn inner()no longer drops the nesting increment. A leading docstring no longer stops the exception, and the expressions in thereturnnow count. (#341, #353) - A conditional expression, a boolean operator sequence, or a comprehension in a
caseguard now counts, at the nesting level of thematch. The guard itself adds nothing, unlike the +1 of anelif. A complex guard can get a C005 plan with help text. (#338, #352) - The decorators and defaults of a module-level
def, the decorators, bases, and keywords of a module-levelclass, and the headers of their direct methods now count toward module scope: the<module>entry with--check-script, and the file total without it. This also holds for an ignored function. Function scores do not change. (#338) - A conditional expression, a boolean operator sequence, or a comprehension now counts in more statement parts: assignment, augmented assignment, annotated assignment,
del,for, andwith ... astargets, thematchsubject, andexcepttypes. The decorators and defaults of a nesteddef, and the decorators, bases, and keywords of a nestedclass, count toward the enclosing function at the nesting level of the definition. Scores of functions that hold these sites go up. A complexmatchsubject orexcepttype can now get a C005 plan, with help text and no suggestion. (#336)
Changed (CLI and output)
--plainprints each function as<path>:<line> <function> <complexity>, so editors and terminals can link to the line. With--suggest-refactors, each plan adds an indented line with its rule id, title, and reduction, for exampleC007 Merge 3 nested if statements (-4); a~marks an estimated reduction. Scripts that parse the first field of a--plainline now get:<line>after the path. (#326)- The C005 helper no longer carries a
-> boolannotation, becauseandandorreturn an operand, not a bool. (#263) - Every CLI warning prints to stderr, and
--quietno longer hides warnings: it hides the report only. The--diffand--stagedwarnings moved from stdout to stderr, so they no longer mix with a report that another tool reads from a pipe. (#294)
Performance
- The aarch64 musllinux wheel allocates with mimalloc, like the x86_64 one. On the django source tree it runs about 4 to 5 times faster. (#303)
Fixed
- A conditional expression counts wherever it sits inside an expression. It used to count only as a statement's value, a positional argument, or an element of a list, tuple, set, or dict value, and counted 0 in a keyword argument, a dict key, a method chain, an attribute, a subscript, a binary operation, an
await, an f-string, a called lambda, a lambda parameter default, or an operand of-,~,not,and, oror, sof(k=a if b else c)scored 0. Boolean operator sequences and comprehensions in the same places count too, so(a or b) + 1now scores 1. Scores rise for functions that use these forms. Thanks to @glictevo. (#334, #335) - The x86_64 musllinux wheel imports again. In 8.3.0 it failed on import with
initial-exec TLS resolves to dynamic definition, because mimalloc used a thread-local storage model that musl cannot load from a Python extension. (#311)
Documentation
- A new AI Agent Workflows page shows how to run complexipy from coding-agent hooks. Thanks to @anhaoXie. (#330)
- The home page shows what complexipy does, and the usage guide is split into focused pages. (#322, #323)
- The ruff comparison and the scores page show the scores this release computes. (#348)
PRs
- feat(cli): add --force-exclude to apply exclude to file arguments by @rohaquinlop in #307
- fix(cli): print every warning to stderr, also under --quiet by @rohaquinlop in #308
- docs(changelog): record the Git 2.30 requirement for --diff and --staged by @rohaquinlop in #309
- ci: catch release-only build and test failures in PR CI by @rohaquinlop in #310
- fix(build): build mimalloc with local-dynamic TLS for the x86_64 musl wheel by @rohaquinlop in #311
- feat(build): use mimalloc on aarch64 musl Linux by @rohaquinlop in #312
- feat(cli): add --explain to print a rule's metadata by @rohaquinlop in #314
- feat(core): apply C005 with --fix through a helper insertion by @rohaquinlop in #316
- feat(lsp): publish diagnostics for unopened files from a workspace scan by @rohaquinlop in #317
- feat(rules): accept rule groups in select and ignore by @rohaquinlop in #318
- feat(lsp): offer refactor plans as code action quick fixes by @rohaquinlop in #319
- docs: keep the downstream snippets on the current release by @rohaquinlop in #320
- fix(docs): render markdown inside the integration blocks on the home page by @rohaquinlop in #322
- docs: show what complexipy does and split the usage guide by @rohaquinlop in #323
- feat(cli): write a single machine-readable report to stdout with --output - by @rohaquinlop in #329
- docs(agents): document hooks for AI agent workflows by @anhaoXie in #330
- feat(json): include function lines and per-line contributions by @rohaquinlop in #331
- feat(cli): show the function line and refactor rule ids in --plain by @rohaquinlop in #332
- feat(diff): list ignore comments the change adds by @rohaquinlop in #333
- fix(core): count conditional expressions nested in any expression by @glictevo in #335
- fix(core): score expressions in statement targets and definition headers by @rohaquinlop in #337
- fix(core): score case guards and module-level definition headers by @rohaquinlop in #343
- fix(core): apply the decorator exception only to a returned nested def by @rohaquinlop in #344
- fix(core): raise nesting for every nested def and walk class bodies by @rohaquinlop in #345
- fix(core): count each function in a recursion cycle by @rohaquinlop in #346
- fix(core): score comprehensions, loop and try else, and mixed boolean operators by @rohaquinlop in #347
- docs: correct stale complexipy scores in the ruff comparison and scores docs by @rohaquinlop in #348
- fix(core): count recursion through lambdas and nested definition headers by @rohaquinlop in #350
- fix(core): nest the else body of for, while, and try by @rohaquinlop in #355
- fix(ci): pin Python in the Rust Tests job so pyo3 can link libpython by @rohaquinlop in #356
- docs(scores): state that a case guard adds nothing of its own by @rohaquinlop in #357
- fix(core): keep the decorator exception when the return wraps the inner function by @rohaquinlop in #358
- test(fixtures): correct score comments in test_try_nested by @rohaquinlop in #359
- feat(core): count recursion through the class name by @rohaquinlop in #360
- fix(core): stop recursion lookup at bindings that hide a function name by @rohaquinlop in #362
- fix(core): resolve a class name bound after every other binding by @rohaquinlop in #364
- fix(core): make recursion resolution near linear and prepare the 9.0.0 notes by @rohaquinlop in #366
- docs: fix the SchemaStore scope and finish the 9.0.0 docs follow-ups by @rohaquinlop in #367
- chore(release): bump version to 9.0.0 by @rohaquinlop in #368
- docs: fix EN and ES consistency findings after the 9.0.0 bump by @rohaquinlop in #369
New Contributors
Full Changelog: 8.3.0...9.0.0