0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Python3] Radonでコードの複雑さを計測する

Last updated at Posted at 2023-05-03

メモ:
Radonの公式ページはこちら
https://radon.readthedocs.io/en/latest/commandline.html

Radonを使うとコードの複雑性であるCyclomatic Complexityを計測することができる。
インストール方法は簡単でpipで入る。

% pip install radon

例えば、下記のmoduleの場合、

radon_example01.py
def main(a):
  if a ==1:
    print("a is 1")
  elif a == 2:
    print("a is 2")
  else:
    print("a is not 1 and 2")

if __name__ == "__main__":
  main(2)

のCyclomatic Complexityは、

% radon cc radon_example01.py -s
radon_example01.py
    F 2:0 main - A (3)

となる。

丸括弧内の数字3はcomplexity scoreと呼ばれる。
分岐が増えるとcomplexity scoreの値は大きくなる。
例えば、

radon_example02.py
def main(a):
  if a ==1:
    print("a is 1")
  elif a == 2:
    print("a is 2")
  elif a == 3:
    print("a is 3")
  elif a == 4:
    print("a is 4")
  elif a == 5:
    print("a is 5")
  else:
    print("a is not 1 and 2")

if __name__ == "__main__":
  main(2)

なら、

% radon cc radon_example02.py -s
radon_example.py
    F 2:0 main - B (6)

という結果となる(complexity scoreは6)
A, BというのはRankを表している。Aが一番低い(複雑でない)

CC score	Rank	Risk
1 - 5	A	low - simple block
6 - 10	B	low - well structured and stable block
11 - 20	C	moderate - slightly complex block
21 - 30	D	more than moderate - more complex block
31 - 40	E	high - complex block, alarming
41+	F	very high - error-prone, unstable block

Cyclomatic Complexity以外にも

raw: compute raw metrics
mi: compute Maintainability Index
hal: compute Halstead complexity metrics

が使えるようである。

奥が深そうなんで、今日はここまで。。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?