Skip to content

Commit 4ac025c

Browse files
authored
feat: add support for match pattern (#227)
* Added support of match pattern * Corrected missing + * Added match statement description into Cyclomatic Complexity doc section. * Added match statement description into Cyclomatic Complexity doc section.
1 parent 84db767 commit 4ac025c

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

docs/intro.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ Complexity. Statements have the following effects on Cyclomatic Complexity:
2222
if +1 An `if` statement is a single decision.
2323
elif +1 The `elif` statement adds another decision.
2424
else +0 The `else` statement does not cause a new decision. The decision is at the `if`.
25+
case pattern +1 The `case pattern` statement is a single decision.
26+
case _ +0 The `case _` statement does not cause a new decision. The decision is at the `case pattern`.
2527
for +1 There is a decision at the start of the loop.
2628
while +1 There is a decision at the `while` statement.
2729
except +1 Each `except` branch adds a new conditional path of execution.

radon/tests/test_complexity_visitor.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,42 @@
8181
4,
8282
{},
8383
),
84+
(
85+
'''
86+
match a:
87+
case 1: pass
88+
''',
89+
2,
90+
{},
91+
),
92+
(
93+
'''
94+
match a:
95+
case 1: pass
96+
case _: pass
97+
''',
98+
2,
99+
{},
100+
),
101+
(
102+
'''
103+
match a:
104+
case 1: pass
105+
case 2: pass
106+
''',
107+
3,
108+
{},
109+
),
110+
(
111+
'''
112+
match a:
113+
case 1: pass
114+
case 2: pass
115+
case _: pass
116+
''',
117+
3,
118+
{},
119+
),
84120
(
85121
'''
86122
for x in range(10): print(x)

radon/visitors.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,13 @@ def generic_visit(self, node):
236236
# Note: Lambda functions are not counted anymore, see #68
237237
elif name in ('If', 'IfExp'):
238238
self.complexity += 1
239+
elif name == 'Match':
240+
# check if _ (else) used
241+
contain_underscore = any(
242+
(case for case in node.cases if
243+
getattr(case.pattern, "pattern", False) is None))
244+
# Max used for case when match contain only _ (else)
245+
self.complexity += max(0, len(node.cases) - contain_underscore)
239246
# The For and While blocks count as 1 plus the `else` block.
240247
elif name in ('For', 'While', 'AsyncFor'):
241248
self.complexity += bool(node.orelse) + 1

0 commit comments

Comments
 (0)