通过 \n 查找可能有问题的字符串连接代码
Finding potentially problematic string concatationing code by \n
在Python中,字符串可以用换行符代替,所以经常会出现想不到的bug。例如:
numbers = (
'zero',
'one',
'two'
'three',
'four',
'five',
)
为了避免这个棘手的问题,我想在将源代码提交到版本库之前使用 Git Hook 检查我要提交的源代码是否有问题。但是由于您可能真的想要组合字符串,我想强制源代码在每个字符串的末尾都有一个逗号,或者在每个字符串的末尾没有逗号。例如:
# ok
numbers = (
'zero'
'one'
'two'
'three'
'four'
'five'
)
# ok
numbers = (
'zero',
'one',
'two',
'three',
'four',
'five',
)
# error
numbers = (
'zero',
'one',
'two',
'three',
'four',
'five'
)
所以我检查了 AST 模块,看 AST 模块是否可以检测到它。结果:
>>> import ast
>>> ast.dump(ast.parse("('1'\n'2')"))
"Module(body=[Expr(value=Str(s='12'))])"
有什么好的解决办法吗?
您正在使用元组,也许使用不同的结构(例如方括号(列表)或有序集)会给您想要的结果。如果我没记错 tupling/untupling 规则,那么您所看到的是将 6 元素元组解包为 1 元素变量的效果 - python 必须对额外的 5 个值做一些事情,并且连接被选为标准行为
在Python中,字符串可以用换行符代替,所以经常会出现想不到的bug。例如:
numbers = (
'zero',
'one',
'two'
'three',
'four',
'five',
)
为了避免这个棘手的问题,我想在将源代码提交到版本库之前使用 Git Hook 检查我要提交的源代码是否有问题。但是由于您可能真的想要组合字符串,我想强制源代码在每个字符串的末尾都有一个逗号,或者在每个字符串的末尾没有逗号。例如:
# ok
numbers = (
'zero'
'one'
'two'
'three'
'four'
'five'
)
# ok
numbers = (
'zero',
'one',
'two',
'three',
'four',
'five',
)
# error
numbers = (
'zero',
'one',
'two',
'three',
'four',
'five'
)
所以我检查了 AST 模块,看 AST 模块是否可以检测到它。结果:
>>> import ast
>>> ast.dump(ast.parse("('1'\n'2')"))
"Module(body=[Expr(value=Str(s='12'))])"
有什么好的解决办法吗?
您正在使用元组,也许使用不同的结构(例如方括号(列表)或有序集)会给您想要的结果。如果我没记错 tupling/untupling 规则,那么您所看到的是将 6 元素元组解包为 1 元素变量的效果 - python 必须对额外的 5 个值做一些事情,并且连接被选为标准行为