1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
# congnitive-complexity
[](https://travis-ci.org/Melevir/cognitive_complexity)
[](https://codeclimate.com/github/Melevir/cognitive_complexity/maintainability)
[](https://codeclimate.com/github/Melevir/cognitive_complexity/test_coverage)
[](https://badge.fury.io/py/cognitive-complexity)

Library to calculate Python functions cognitive complexity via code.
## Installation
```bash
pip install cognitive_complexity
```
## Usage
```python
>>> import ast
>>> funcdef = ast.parse("""
... def f(a):
... return a * f(a - 1) # +1 for recursion
... """).body[0]
>>> from cognitive_complexity.api import get_cognitive_complexity
>>> get_cognitive_complexity(funcdef)
1
```
## What is cognitive complexity
Here are some readings about cognitive complexity:
- [Cognitive Complexity, Because Testability != Understandability](https://blog.sonarsource.com/cognitive-complexity-because-testability-understandability);
- [Cognitive Complexity: A new way of measuring understandability](https://www.sonarsource.com/docs/CognitiveComplexity.pdf),
white paper by G. Ann Campbell;
- [Cognitive Complexity: the New Guide to Refactoring for Maintainable Code](https://www.youtube.com/watch?v=5C6AGTlKSjY);
- [Cognitive Complexity](https://docs.codeclimate.com/docs/cognitive-complexity)
from CodeClimate docs;
- [Is Your Code Readable By Humans? Cognitive Complexity Tells You](https://www.tomasvotruba.cz/blog/2018/05/21/is-your-code-readable-by-humans-cognitive-complexity-tells-you/).
## Realization details
This is not precise realization of original algorithm
proposed by [G. Ann Campbell](https://github.com/ganncamp),
but it gives rather similar results.
The algorithm gives complexity points for breaking control flow, nesting,
recursion, stacks logic operation etc.
## Contributing
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:
- You can run all checks and tests with `make check`. Please do it
before TravisCI does.
- We use [BestDoctor python styleguide](https://github.com/best-doctor/guides/blob/master/guides/python_styleguide.md).
Sorry, styleguide is available only in Russian for now.
- We respect [Django CoC](https://www.djangoproject.com/conduct/).
Make soft, not bullshit.
|