Cognitive Complexity

1.3.0 · active · verified Thu Apr 16

Cognitive-complexity is a Python library designed to calculate the cognitive complexity of Python functions by analyzing their Abstract Syntax Trees (ASTs). Unlike cyclomatic complexity, cognitive complexity aims to measure how difficult code is for a human to understand, focusing on flow breaks, nesting, and other structures that increase mental effort. The current version is 1.3.0, released in August 2022, with a relatively low release cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to parse a Python code snippet into an Abstract Syntax Tree (AST) using the built-in `ast` module, then calculate its cognitive complexity using `get_cognitive_complexity` from the `cognitive_complexity.api` module. The result is an integer representing the cognitive complexity score.

import ast
from cognitive_complexity.api import get_cognitive_complexity

code_snippet = """
def complex_function(a):
    if a > 0:
        for i in range(a):
            if i % 2 == 0:
                # This is a recursive call example
                return a * complex_function(a - 1)
    return 0
"""

# Parse the code into an AST
tree = ast.parse(code_snippet)

# The library expects a FunctionDef node (or similar, like AsyncFunctionDef)
# In this simple example, the first element of tree.body is our function definition
function_node = tree.body[0]

# Calculate cognitive complexity
complexity = get_cognitive_complexity(function_node)
print(f"Cognitive Complexity of 'complex_function': {complexity}")

view raw JSON →