Cognitive Complexity
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
-
ModuleNotFoundError: No module named 'cognitive_complexity.api'
cause The `cognitive-complexity` package was either not installed, or the import path is incorrect. People often try `import cognitive_complexity` which does not expose the API directly.fixEnsure the package is installed (`pip install cognitive-complexity`) and use the correct import statement: `from cognitive_complexity.api import get_cognitive_complexity`. -
AttributeError: '_ast.Module' object has no attribute 'lineno'
cause The `get_cognitive_complexity` function expects a specific AST node type, typically `ast.FunctionDef` (for a function definition) or `ast.AsyncFunctionDef`. Passing the entire module AST (`ast.parse(...)`) directly without selecting a function node will cause this error.fixAfter parsing the code with `ast.parse(code)`, access the specific function definition node (e.g., `tree.body[0]` if it's the first top-level item) before passing it to `get_cognitive_complexity`. -
Cognitive complexity score differs from other tools like SonarQube or complexipy.
cause This library's implementation of the cognitive complexity algorithm is not an exact replication of SonarSource's original specification and may differ from other tools that adhere strictly to that definition.fixThis is expected behavior due to implementation differences. If strict adherence to a specific cognitive complexity standard is required, verify if this library meets those requirements or consider alternative tools like `complexipy`.
Warnings
- gotcha The library's implementation of cognitive complexity is not a precise realization of the original algorithm proposed by G. Ann Campbell (SonarSource). While it aims for similar results, direct comparisons with tools strictly following the SonarSource definition may show discrepancies.
- gotcha The library might have limitations in robustly identifying and scoring all forms of recursion, potentially leading to inaccurate complexity increments for recursive calls in certain scenarios. The example usage often includes a manual '+1 for recursion' comment, indicating a potential area for misinterpretation or undercounting.
- breaking The library requires Python 3.6 or higher. Attempting to use it with older Python versions (e.g., Python 2.x or Python 3.5) will result in installation failures or runtime errors.
Install
-
pip install cognitive-complexity
Imports
- get_cognitive_complexity
from cognitive_complexity.api import get_cognitive_complexity
- ast
import ast
Quickstart
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}")