McCabe Code Complexity Checker
McCabe is a Python library that provides a plugin for flake8, the Python code checker. It's used to analyze the cyclomatic complexity (McCabe complexity) of functions and methods in Python code, helping developers identify potentially over-complex code that might be difficult to understand, test, or maintain. The current version is 0.7.0. Its release cadence is slow, often aligning with updates to supported Python versions.
Warnings
- breaking Version 0.7.0 and later dropped support for Python versions older than 3.6.
- gotcha When used with flake8, the mccabe plugin is disabled by default. You must explicitly enable it by setting the maximum complexity threshold.
- gotcha To ignore a specific McCabe complexity violation (C901) for a function, the `# noqa: C901` comment must be placed on the function definition line, not just any line within the function.
Install
-
pip install mccabe flake8 -
pip install mccabe
Imports
- McCabeChecker
from mccabe import McCabeChecker
Quickstart
# To analyze a file using mccabe via flake8:
# 1. Install both libraries
# pip install mccabe flake8
# 2. Run flake8 with the --max-complexity flag
# (e.g., to flag functions with complexity > 10)
# flake8 --max-complexity 10 your_module.py
# Example of a simple Python file to check:
# your_module.py
def high_complexity_function(a, b):
if a > 0:
if b > 0:
print('Both positive')
else:
print('A positive, B not')
elif a < 0:
if b < 0:
print('Both negative')
else:
print('A negative, B not')
else:
print('A is zero')
# To use mccabe as a standalone script (less common):
# python -m mccabe --min 5 your_module.py