{"id":7094,"library":"cognitive-complexity","title":"Cognitive Complexity","description":"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.","status":"active","version":"1.3.0","language":"en","source_language":"en","source_url":"https://github.com/Melevir/cognitive_complexity","tags":["code quality","complexity","cognitive complexity","static analysis","linter"],"install":[{"cmd":"pip install cognitive-complexity","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Used in examples for unparsing AST nodes to code strings for display; not a core dependency for complexity calculation itself.","package":"astunparse","optional":true},{"reason":"Used in examples for pretty-printing results; not a core dependency for complexity calculation itself.","package":"tabulate","optional":true}],"imports":[{"symbol":"get_cognitive_complexity","correct":"from cognitive_complexity.api import get_cognitive_complexity"},{"note":"Used to parse Python code into an Abstract Syntax Tree (AST) before analysis.","symbol":"ast","correct":"import ast"}],"quickstart":{"code":"import ast\nfrom cognitive_complexity.api import get_cognitive_complexity\n\ncode_snippet = \"\"\"\ndef complex_function(a):\n    if a > 0:\n        for i in range(a):\n            if i % 2 == 0:\n                # This is a recursive call example\n                return a * complex_function(a - 1)\n    return 0\n\"\"\"\n\n# Parse the code into an AST\ntree = ast.parse(code_snippet)\n\n# The library expects a FunctionDef node (or similar, like AsyncFunctionDef)\n# In this simple example, the first element of tree.body is our function definition\nfunction_node = tree.body[0]\n\n# Calculate cognitive complexity\ncomplexity = get_cognitive_complexity(function_node)\nprint(f\"Cognitive Complexity of 'complex_function': {complexity}\")","lang":"python","description":"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."},"warnings":[{"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.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"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.","severity":"gotcha","affected_versions":"All versions (specifically 0.0.x and 1.x.x)"},{"fix":"Ensure your project environment uses Python 3.6 or a newer compatible version.","message":"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.","severity":"breaking","affected_versions":"<3.6"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Ensure the package is installed (`pip install cognitive-complexity`) and use the correct import statement: `from cognitive_complexity.api import get_cognitive_complexity`.","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.","error":"ModuleNotFoundError: No module named 'cognitive_complexity.api'"},{"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`.","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.","error":"AttributeError: '_ast.Module' object has no attribute 'lineno'"},{"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`.","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.","error":"Cognitive complexity score differs from other tools like SonarQube or complexipy."}]}