Nested Ternary

ID

python.nested_ternary

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Python

Tags

code-style, complexity

Description

Reports a Python conditional expression (a if cond else b) nested inside another conditional expression. Stacked conditionals are notoriously hard to read — the language binds inside-out while the eye reads left-to-right, so the reader has to mentally re-bracket every chain.

size = "small" if x < 10 else "medium" if x < 100 else "large"   # FLAW

# better
if x < 10:
    size = "small"
elif x < 100:
    size = "medium"
else:
    size = "large"

Rationale

Two-way ternaries are short and obvious; three-way and deeper chains stop being short or obvious. The cost of converting them to a real if/elif chain is a couple of lines, and every reader after you wins.

Remediation

  • Convert the chain to an if/elif/else block.

  • For value mappings, replace with a dict lookup: MAPPING.get(x, default).

  • Extract a helper if the same chain repeats.