如何分析 Python 代码以识别有问题的区域?

我有一个跨多个项目的大型源代码存储库。我想生成一个关于源代码健康状况的报告,确定需要解决的问题领域。

具体来说,我希望调出具有高循环复杂度的例程,识别重复,或者运行一些 lint-like 静态分析来发现可疑的(因此可能是错误的)结构。

我该如何着手编写这样一份报告呢?

41752 次浏览

For static analysis there is pylint and pychecker. Personally I use pylint as it seems to be more comprehensive than pychecker.

For cyclomatic complexity you can try this perl program, or this article which introduces a python program to do the same

Thanks to Pydev, you can integrate pylint in the Eclipse IDE really easily and get a code report each time you save a modified file.

For measuring cyclomatic complexity, there's a nice tool available at traceback.org. The page also gives a good overview of how to interpret the results.

+1 for pylint. It is great at verifying adherence to coding standards (be it PEP8 or your own organization's variant), which can in the end help to reduce cyclomatic complexity.

There is a tool called CloneDigger that helps you find similar code snippets.

Pycana works like charm when you need to understand a new project!

PyCAna (Python Code Analyzer) is a fancy name for a simple code analyzer for python that creates a class diagram after executing your code.

See how it works: http://pycana.sourceforge.net/

output:

alt text

For cyclomatic complexity you can use radon: https://github.com/rubik/radon

(Use pip to install it: pip install radon)

Additionally it also has these features:

  • raw metrics (these include SLOC, comment lines, blank lines, &c.)
  • Halstead metrics (all of them)
  • Maintainability Index (the one used in Visual Studio)

Use flake8, which provides pep8, pyflakes, and cyclomatic complexity analysis in one tool

For checking cyclomatic complexity, there is of course the mccabe package.

Installation:

$ pip install --upgrade mccabe

Usage:

$ python -m mccabe --min=6 path/to/myfile.py

Note the threshold of 6 above. Per this answer, scores >5 probably should be simplified.

Sample output with --min=3:

68:1: 'Fetcher.fetch' 3
48:1: 'Fetcher._read_dom_tag' 3
103:1: 'main' 3

It can optionally also be used via pylint-mccabe or pytest-mccabe, etc.