这段代码有几处不合规
同一件事,四个人四种写法
各写各的
统一之后
一段十一行的示例代码:
1 import os 2 3 def CalcTotal(items): 4 total = 0␣␣␣ 5 for i in items: 6 total = total + i␣␣␣ 7 unused = 42 8 return total 9 10 def calcAverage(items, weights, extra_config_value): 11 return CalcTotal(items) / len(items)
(␣ 表示一个看不见的行尾空格)
按四条规则检查:行尾空格、行太长、函数名不是小写下划线、变量赋了值却没用过。运行下面这段程序:
import re
def is_snake(name):
return re.fullmatch(r"[a-z_][a-z0-9_]*", name) is not None
import re
def lint(src, maxlen=45):
out = []
for i, l in enumerate(src, 1):
if l != l.rstrip():
out.append((i, "E101"))
if len(l) > maxlen:
out.append((i, "E102"))
m = re.match(r"def\s+(\w+)\s*\(", l)
if m and not is_snake(m.group(1)):
out.append((i, "E201"))
for i, l in enumerate(src, 1):
m = re.match(r"\s*(\w+)\s*=\s*", l)
if not m:
continue
name = m.group(1)
used = any(re.search(r"\b" + name + r"\b", x)
for j, x in enumerate(src, 1)
if j != i and not re.match(r"\s*" + name + r"\s*=", x))
if not used:
out.append((i, "E301"))
return sorted(out)
src = ['import os',
'',
'def CalcTotal(items):',
' total = 0 ',
' for i in items:',
' total = total + i ',
' unused = 42',
' return total',
'',
'def calcAverage(items, weights, extra_config_value):',
' return CalcTotal(items) / len(items)']
print(len(lint(src)))
全部评论