跑完 formatter 还剩几处问题
那段示例代码原本有 5 处问题。formatter 只能修行尾空格和行太长这两类。运行下面这段程序:
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)
def run_formatter(src, maxlen=45):
out = []
for l in src:
l = l.rstrip()
if len(l) > maxlen and ", " in l:
head, _, tail = l.partition("(")
l = head + "(\n " + tail.replace(", ", ",\n ")
out.append(l)
return "\n".join(out).split("\n")
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(str(len(lint(src))) + "/" + str(len(lint(run_formatter(src)))))
全部评论