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-complexityVerified import paths — ran on the pinned version, not inferred.
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.
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.
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.
Ensure your project environment uses Python 3.6 or a newer compatible version.
Ensure the package is installed (`pip install cognitive-complexity`) and use the correct import statement: `from cognitive_complexity.api import get_cognitive_complexity`.
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`.
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`.