mik*_*ike 1 python string-concatenation
最近我们在代码中发现了一些错误,因为开发人员忘记在字符串列表中添加逗号而python只是连接字符串.往下看:
目标清单是:["abc","def"]
开发人员写道:["abc""def"]
我们得到了:["abcdef"]
现在我担心代码其他部分的类似错误,这个功能是python的核心部分吗?有可能禁用它吗?
允许使用多个相邻的字符串文字(由空格分隔),可能使用不同的引用约定,并且它们的含义与它们的连接相同.因此,
"hello" 'world'相当于"helloworld".
我不认为有一种方法可以禁用它,而不是攻击Python本身.
但是,您可以使用下面的脚本来标记您的代码,并在找到多个相邻字符串时发出警告:
import tokenize
import token
import io
import collections
class Token(collections.namedtuple('Token', 'num val start end line')):
@property
def name(self):
return token.tok_name[self.num]
def check(codestr):
lastname = None
for tok in tokenize.generate_tokens(io.BytesIO(codestr).readline):
tok = Token(*tok)
if lastname == 'STRING' and lastname == tok.name:
print('ADJACENT STRINGS: {}'.format(tok.line.rstrip()))
else:
lastname = tok.name
codestr = '''
'hello'\
'world'
for z in ('foo' 'bar', 'baz'):
x = ["abc" "def"]
y = [1, 2, 3]
'''
check(codestr)
Run Code Online (Sandbox Code Playgroud)
产量
ADJACENT STRINGS: 'hello''world'
ADJACENT STRINGS: for z in ('foo' 'bar', 'baz'):
ADJACENT STRINGS: x = ["abc" "def"]
Run Code Online (Sandbox Code Playgroud)