Registry / testing / cognitive-complexity

cognitive-complexity

JSON →
library1.3.0pypypi✓ verified 87d ago

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.

pip install cognitive-complexity
INSTALL
IMPORT
SIG · COGNITIVE-COMPLEXI
C
cognitive-complexity
testingpythonv1.3.0
Install
2.7s avg
Import
15ms
Disk
20MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.3.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 0.016s · 19.2MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 2.7s · import 0.014s · 20MB
20MB installed
● package 20MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

get_cognitive_complexity
from cognitive_complexity.api import get_cognitive_complexity
ast
import ast
Used to parse Python code into an Abstract Syntax Tree (AST) before analysis.

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}")
Debug
Known issues
gotchaThe 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.
fix
Be aware that scores might not perfectly align with other tools. Consult the library's source for its specific scoring logic if precise matching is critical.
affects: All versions
gotchaThe 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.
fix
Manually review code with complex recursive structures if the cognitive complexity score seems unusually low, as the automatic detection might not cover all edge cases.
affects: All versions (specifically 0.0.x and 1.x.x)
breakingThe 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.
fix
Ensure your project environment uses Python 3.6 or a newer compatible version.
affects: <3.6
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'cognitive_complexity.api'
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.
fix
Ensure 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'
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.
fix
After 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.
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.
fix
This 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`.
Upgrade
Version history
1.3.0latest on PyPI · released Aug 9, 2022
Audit
Dependencies
astunparseoptionalUsed in examples for unparsing AST nodes to code strings for display; not a core dependency for complexity calculation itself.
tabulateoptionalUsed in examples for pretty-printing results; not a core dependency for complexity calculation itself.
Agent activity
12 hits · last 30 days
node
10
OpenAI (training)
2
Resources
cognitive-complexity — pip install cognitive-complexity · libregistry