flake8-cognitive-complexity
An extension for flake8 that validates cognitive functions complexity. Cognitive complexity is an analog of cyclomatic complexity, measuring how difficult a piece of code is to understand, as introduced by G. Ann Campbell and used by SonarSource and CodeClimate. The library is currently at version 0.1.0 and has seen limited releases since its initial upload in 2020, suggesting a stable but not actively developed state.
Common errors
-
CCR001 Cognitive complexity is too high (X > Y)
cause A function's cognitive complexity calculation exceeds the configured or default maximum threshold (default 7).fixRefactor the function to reduce its complexity. This can involve splitting it into smaller functions, reducing nesting levels, simplifying conditional logic, or extracting helper methods. Alternatively, increase the `max-cognitive-complexity` threshold in your `flake8` configuration. -
flake8: command not found
cause The `flake8` executable is not found in the system's PATH, typically because it's not installed or the virtual environment where it's installed is not active.fixInstall `flake8` in your current Python environment using `pip install flake8`. If using a virtual environment, ensure it is activated before running `flake8`. -
Error: No such option: --max-cognitive-complexity
cause The `flake8-cognitive-complexity` plugin is not correctly installed, or `flake8` cannot discover it in the current Python environment.fixVerify that `pip install flake8-cognitive-complexity` was executed in the same Python environment that `flake8` is running from. You can check if the plugin is detected by running `flake8 --version` and looking for 'cognitive-complexity' in the output. If it's not there, reinstall the plugin or check your environment setup.
Warnings
- gotcha The library has had only one release (0.1.0) since July 2020. This suggests infrequent updates and potentially unaddressed issues or lack of active development. Consider its long-term support and compatibility with newer Python and Flake8 versions.
- gotcha The default cognitive complexity threshold is 7. Projects with existing complex codebases might generate numerous warnings upon initial integration. This may require a higher threshold initially or gradual refactoring to meet the default.
- gotcha As a `flake8` plugin, `flake8-cognitive-complexity`'s compatibility is tied to the `flake8` version. The README notes testing on `flake8 3.7.8`. Newer `flake8` versions might introduce subtle incompatibilities with older plugins.
Install
-
pip install flake8-cognitive-complexity
Quickstart
# test_code.py
def f(a, b):
if a:
for i in range(b):
if b:
return 1
# Save the above as test_code.py
# To run from terminal (after 'pip install flake8 flake8-cognitive-complexity'):
# flake8 test_code.py
# flake8 --max-cognitive-complexity=3 test_code.py