Skip to content

Count a ternary once in cyclomatic complexity - #20

Open
rganz wants to merge 1 commit into
graydwarf:mainfrom
rganz:fix/ternary-double-count
Open

rganz wants to merge 1 commit into
graydwarf:mainfrom
rganz:fix/ternary-double-count

Conversation

@rganz

@rganz rganz commented Sep 14, 2026

Copy link
Copy Markdown

Fixes the double count reported in #16.

_calculate_cyclomatic_complexity added two for any line holding a ternary. The statement test fired on if appearing anywhere in the line, and the ternary count then fired again for the same occurrence. The statement test now matches only a line beginning with if .

Measured on a probe project against this tree, one change at a time:

function before after
only decision point is one ternary 3 2
if, and, elif, or, for, while, one ternary 9 8

The second one is 8 by hand count, so the fix removes the double count and touches no other decision point.

One case it does not address, and does not make worse: a line beginning with if that also holds a ternary is still counted once, because the ternary rule already excludes such lines.

Three other defects in the same function are left for separate changes: match counted once whatever its arm count, keywords inside string literals read as code, and physical-line scanning that drops an operator opening a \-continued line. The last was found after #16 and is the largest; repro there.

_calculate_cyclomatic_complexity added two for any line holding a ternary,
because two rules matched the same text: the statement test also fired on
" if " anywhere in the line, and the ternary count then fired again for the
same occurrence.

The statement test now matches only a line that begins with "if ", leaving
in-line occurrences to the ternary rule that already handles them.

Measured on a probe project against this tree. A function whose only decision
point is one ternary went from 3 to 2, which is the correct value for base 1
plus one branch. A function with if, and, elif, or, for, while and one ternary
went from 9 to 8, hand counted as 8. No other decision point changes.

This matters beyond the number because _check_complexity assigns critical
severity above cyclomatic_critical, so the over-count can fail a CI gate for
complexity a function does not have.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant