Cyclomatic complexity metric practices for Python

wemake-python-styleguide supports both radon and mccabe implementations of Cyclomatic Complexity.

There are also different complexity metrics that are not covered by just Cyclomatic Complexity, including:

  • Number of function decorators; lower is better
  • Number of arguments; lower is better
  • Number of annotations; higher is better
  • Number of local variables; lower is better
  • Number of returns, yields, awaits; lower is better
  • Number of statements and expressions; lower is better

Read more about why it is important to obey them: https://sobolevn.me/2019/10/complexity-waterfall

They are all covered by wemake-python-styleguide. Repo: https://github.com/wemake-services/wemake-python-styleguide Docs: https://wemake-python-stylegui.de


Python isn't special when it comes to cyclomatic complexity. CC measures how much branching logic is in a chunk of code.

Experience shows that when the branching is "high", that code is harder to understand and change reliably than code in which the branching is lower.

With metrics, it typically isn't absolute values that matter; it is relative values as experienced by your organization. What you should do is to measure various metrics (CC is one) and look for a knee in the curve that relates that metric to bugs-found-in-code. Once you know where the knee is, ask coders to write modules whose complexity is below the knee. This is the connection to long-term maintenance.

What you don't measure, you can't control.


We used the RADON tool in one of our projects which is related to Test Automation.

RADON

Depending on new features and requirements, we need to add/modify/update/delete codes in that project. Also, almost 4-5 people were working on this. So, as a part of review process, we identified and used RADON tools since we want our code maintainable and readable.

Depend on the RADON tool output, there were several times we re-factored our code, added more methods and modified the looping.

Please let me know if this is useful to you.