sourcery_analytics.metrics.cyclomatic_complexity

Cyclomatic complexity calculations.

Cyclomatic complexity is a measure of the number of “pathways” through a piece of code, developed as an aid to writing tests. A high cyclomatic complexity can indicate a piece of code may have too much branching logic.

For implementation details see methods below.

sourcery_analytics.metrics.cyclomatic_complexity.method_cyclomatic_complexity(method: FunctionDef) int

The total cyclomatic complexity of a method.

Parameters

method – a node for a function definition

Examples

>>> method_cyclomatic_complexity(
...     "def div(x, y): return None if y == 0 else x / y"
... )
2
sourcery_analytics.metrics.cyclomatic_complexity.total_cyclomatic_complexity(node: NodeNG) int

Computes the total cyclomatic complexity within a node.

Parameters

node – any node in an astroid syntax tree

Examples

>>> total_cyclomatic_complexity('''if x: pass''')
1
sourcery_analytics.metrics.cyclomatic_complexity.cyclomatic_complexity(_node: NodeNG, /) int
sourcery_analytics.metrics.cyclomatic_complexity.cyclomatic_complexity(node: TryExcept)
sourcery_analytics.metrics.cyclomatic_complexity.cyclomatic_complexity(node: BoolOp)
sourcery_analytics.metrics.cyclomatic_complexity.cyclomatic_complexity(node: If)
sourcery_analytics.metrics.cyclomatic_complexity.cyclomatic_complexity(_node: IfExp)
sourcery_analytics.metrics.cyclomatic_complexity.cyclomatic_complexity(node: For)
sourcery_analytics.metrics.cyclomatic_complexity.cyclomatic_complexity(node: While)
sourcery_analytics.metrics.cyclomatic_complexity.cyclomatic_complexity(node: Comprehension)

The cyclomatic complexity for a single node.

Cyclomatic complexity is context-free and so doesn’t need a visitor to evaluate.

  • Try/Except statements return the number of except (and else) blocks.

  • Boolean operations return one less than the number of compared values.

  • If statements and expressions return 1, plus 1 for each “else” or “elif”.

  • For and while statements return 1, plus 1 for any “else”.

  • Comprehensions return 1 plus the number of conditions.