Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(health): a Python conditional-expression chain nests like an elif dispatch (#3338)
Shahab Ahmed41bf297d57a4
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/README.md b/packages/core/src/repowise/core/analysis/health/complexity/README.mdindex fecd9e47a..662e4050c 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/README.md+++ b/packages/core/src/repowise/core/analysis/health/complexity/README.md@@ -29,7 +29,9 @@ Tree-sitter AST walker. Single AST pass per file computes:(`&&`, `||`).- **max nesting depth** — deepest nested control-flow block per function.`else if` arms and, in TS/JS, ternary chain arms and ternaries choosing- JSX (`flat_ternary_kinds`) add CCN and a flat +1 cognitive but no level.+ JSX (`flat_ternary_kinds`), plus Python conditional-expression chains+ (`1 if a else 2 if b else 3`), add CCN and a flat +1 cognitive but no+ level.- **cognitive complexity** — SonarSource-style weighted nesting cost(each level adds an incrementing penalty, plus +1 for each break incontrol flow).diff --git a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.pyindex 021838b87..ae55ee9f3 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py@@ -134,14 +134,33 @@ def _unparen(node: Node | None) -> Node | None:return node+def _ternary_else_arm(node: Node, lmap: LanguageNodeMap) -> Node | None:+ """The else-arm of a ternary: its ``alternative`` where the grammar names+ it, else its last named child.++ A positional grammar (``ternary_arms_positional``) spells the arms as the+ node's first and last named children instead of ``consequence`` /+ ``alternative`` fields — Python's ``X if C else Y`` orders them+ ``X``, ``C``, ``Y``. Locating the else-arm by position lets a chain arm be+ recognised as flat for those languages too.+ """+ arm = node.child_by_field_name("alternative")+ if arm is not None:+ return arm+ if lmap.ternary_arms_positional and node.named_children:+ return node.named_children[-1]+ return None++def _is_flat_ternary(node: Node, lmap: LanguageNodeMap, in_markup: bool) -> bool:"""A ternary that chooses rather than nests (see ``flat_ternary_kinds``).That is one rendered inside JSX, one with a JSX branch, or an arm of a- chain (the ``alternative`` of a ternary of its kind). A ternary in another's- ``consequence`` still nests: that is a decision inside a decision. Outside- markup a branch must itself be JSX, so ``cond ? c2 && <A/> : x`` nests.- Like an ``else if``, a flat ternary costs a flat +1 cognitive.+ chain (the else-arm, per ``_ternary_else_arm``, of a ternary of its kind).+ A ternary in another's ``consequence`` still nests: that is a decision+ inside a decision. Outside markup a branch must itself be JSX, so+ ``cond ? c2 && <A/> : x`` nests. Like an ``else if``, a flat ternary costs+ a flat +1 cognitive."""if node.type not in lmap.flat_ternary_kinds:return False@@ -151,7 +170,7 @@ def _is_flat_ternary(node: Node, lmap: LanguageNodeMap, in_markup: bool) -> boolwhile parent is not None and parent.type == "parenthesized_expression":parent = parent.parentif parent is not None and parent.type == node.type:- alternative = _unparen(parent.child_by_field_name("alternative"))+ alternative = _unparen(_ternary_else_arm(parent, lmap))if alternative is not None and alternative.id == node.id:return Truereturn any(diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.pyindex f845a126c..a64e457e4 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py@@ -69,6 +69,12 @@ class LanguageNodeMap:# (``a ? x : b ? y : z``, a dispatch) or a choice between markup (JSX).# Still a CCN point; no nesting level. Empty keeps every ternary nesting.flat_ternary_kinds: frozenset[str] = frozenset()+ # Some grammars spell a ternary's branches positionally instead of naming+ # them ``consequence`` / ``alternative`` (Python's ``X if C else Y`` has no+ # field names: the arms are its first and last named children). For those+ # the else-arm is the node's last named child, so a chain arm can still be+ # located by position and recognised as flat.+ ternary_arms_positional: bool = False# ------------------------------------------------------------------# Class-level analysis (LCOM4 / god-class). All three fields default@@ -353,6 +359,11 @@ _PY = LanguageNodeMap(# branch kinds. The comprehension ``for`` (``for_in_clause``) is a generator,# not a decision, so it is intentionally left out.branch_kinds=frozenset({"if_statement", "elif_clause", "conditional_expression", "if_clause"}),+ # A conditional-expression chain (``1 if a else 2 if b else 3``) reads like+ # an ``elif`` dispatch: each else-arm chooses rather than nests. The grammar+ # names no branch fields, so the arm is found positionally.+ flat_ternary_kinds=frozenset({"conditional_expression"}),+ ternary_arms_positional=True,loop_kinds=frozenset({"for_statement", "while_statement"}),try_kinds=frozenset({"try_statement"}),catch_kinds=frozenset({"except_clause"}),diff --git a/tests/unit/health/test_jsx_ternary_nesting.py b/tests/unit/health/test_jsx_ternary_nesting.pyindex 006dcaf84..5b0c098bb 100644--- a/tests/unit/health/test_jsx_ternary_nesting.py+++ b/tests/unit/health/test_jsx_ternary_nesting.py@@ -216,7 +216,43 @@ export function Maybe({ a, b }: Props) {assert _fn(src, "Maybe").max_nesting == 1-def test_python_conditional_expression_chain_unchanged():+def test_python_conditional_expression_chain_is_flat():+ # ``#3278`` left Python nesting a conditional-expression chain one level+ # per arm; the chain now reads like an ``elif`` dispatch. The else-arm of+ # ``X if C else Y`` is the node's last named child (the grammar names no+ # ``alternative`` field), so the arm is found positionally.src = "def f(a, b):\n return 1 if a else 2 if b else 3\n"fn = _fn(src, "f", "python", "/tmp/f.py")- assert (fn.ccn, fn.max_nesting) == (3, 2)+ assert (fn.ccn, fn.max_nesting) == (3, 1)+ assert fn.cognitive == 2 # head 1 + a flat 1 per arm, like an ``elif``+++def test_python_longer_chain_is_flat():+ src = (+ "def f(a, b, c):\n"+ " return 1 if a else 2 if b else 3 if c else 4\n"+ )+ fn = _fn(src, "f", "python", "/tmp/f.py")+ assert fn.ccn == 4+ assert fn.max_nesting == 1 # the head opens one level, the arms none+ assert fn.cognitive == 3+++def test_python_parenthesized_chain_arm_is_flat():+ src = "def f(a, b, c):\n return 1 if a else (2 if b else 3)\n"+ fn = _fn(src, "f", "python", "/tmp/f.py")+ assert fn.max_nesting == 1+++def test_python_conditional_in_a_consequence_still_nests():+ # A conditional in another's consequence is a decision inside a decision.+ src = "def g(a, b):\n return (1 if a else 2) if b else 3\n"+ fn = _fn(src, "g", "python", "/tmp/g.py")+ assert fn.max_nesting == 2+++def test_python_conditional_inside_an_if_still_nests():+ # The ``if`` opens a level; the conditional inside it opens a second.+ src = "def h(a, b):\n if a:\n return 1 if b else 2\n return 0\n"+ fn = _fn(src, "h", "python", "/tmp/h.py")+ assert fn.max_nesting == 2