Library to calculate Python functions cognitive complexity via code.
pip install cognitive_complexity
>>> import ast >>> funcdef = ast.parse(""" ... def f(a): ... return a * f(a - 1) # +1 for recursion ... """).body >>> from cognitive_complexity.api import get_cognitive_complexity >>> get_cognitive_complexity(funcdef) 1
Perhaps the most common way to use this library (especially if you are already using the Flake8 linter) is to use the flake8-cognitive-complexity extension. If you run Flake8 with this extension installed, Flake8 will let you know if your code is too complex. For more details and documentation, visit the flake8-cognitive-complexity extension repository.
What is cognitive complexity
Here are some readings about cognitive complexity:
- Cognitive Complexity, Because Testability != Understandability;
- Cognitive Complexity: A new way of measuring understandability, white paper by G. Ann Campbell;
- Cognitive Complexity: the New Guide to Refactoring for Maintainable Code;
- Cognitive Complexity from CodeClimate docs;
- Is Your Code Readable By Humans? Cognitive Complexity Tells You.
This is not precise realization of original algorithm proposed by G. Ann Campbell, but it gives rather similar results. The algorithm gives complexity points for breaking control flow, nesting, recursion, stacks logic operation etc.
We would love you to contribute to our project. It's simple:
- Create an issue with bug you found or proposal you have. Wait for approve from maintainer.
- Create a pull request. Make sure all checks are green.
- Fix review comments if any.
- Be awesome.
Here are useful tips: