PyCQA / PyCQA/mccabe

[Proposal] Add Cognitive Complexity as new option

Open
#112 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
681
Forks
65
PR merge metrics
No merged PRs in 30d

Description

Introduction

I would like to request to add "Cognitive Complexity" to this library as an option to select in the CLI and through hooks. This is a common quality check in the SonarQube application, used by many for static code checking.

Please see this document written by Sonar: https://www.sonarsource.com/docs/CognitiveComplexity.pdf. Importantly: "Unlike Cyclomatic Complexity, Cognitive Complexity adds a fundamental increment for each method in a recursion cycle, whether direct or indirect".

I am curious as to the opinions of others :)

Example 1

I like the example in the PDF, where the Cyclomatic Complexity is the same, but the Cognitive Complexity is vastly different:
image

image

Example 2

Consider the following code:

for _ in [i for i in range(5)]:
    for _ in [i for i in range(5)]:
        for _ in [i for i in range(5)]:
            for j in [i for i in range(5)]:
                if j == 2:
                    ...
                else:
                    if j > 3:
                        ...

The Cyclomatic Complexity, also the one currently reported bymccabe, is 7:
image

The Cognitive Complexity, as reported by Sonar, is 22 due to all of the nesting.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the requested Cognitive Complexity definition in the linked Sonar document, then inspect the CLI and hooks entry points mentioned in the issue. Define how the metric should handle nesting and recursion, and verify that it can be selected and reported through both interfaces.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.