标识隐式字符串文本连接

2024-09-28 03:21:53 发布

您现在位置:Python中文网/ 问答频道 /正文

According to guido(以及对其他一些Python程序员来说),隐式字符串文本连接被认为是有害的。因此,我试图识别包含这种连接的逻辑行。在

我的第一次(也是唯一一次)尝试是使用shlex;我想用posix=False分割一条逻辑行,因此我将标识用引号封装的部分,如果这些部分相邻,则将被视为“文字连接”。在

但是,这在多行字符串上失败,如下例所示:

shlex.split('""" Some docstring """', posix=False)
# Returns '['""', '" Some docstring "', '""']', which is considered harmful, but it's not

我可以调整这是一些奇怪的特别的方式,但我想知道你是否能想出一个简单的解决办法。我的目的是将它添加到已经扩展的pep8验证器中。在


Tags: to字符串文本falsesome逻辑标识引号
3条回答

我决定使用来自user2357112的建议,并对其进行一点扩展以获得以下解决方案,我在这里将其描述为pep8模块的扩展:

def python_illegal_concetenation(logical_line):
    """
    A language design mistake from the early days of Python.
    https://mail.python.org/pipermail/python-ideas/2013-May/020527.html

    Okay: val = "a" + "b"
    W610: val = "a" "b"
    """
    w = "W610 implicit string literal concatenation considered harmful"
    sio = StringIO.StringIO(logical_line)
    tgen = tokenize.generate_tokens(sio.readline)
    state = None
    for token_type, _, (_, pos), _, _ in tgen:
      if token_type == tokenize.STRING:
        if state == tokenize.STRING:
          yield pos, w
        else:
          state = tokenize.STRING
      else:
        state = None

更好地处理这一问题的一个方法是,当您有一个列表时,在右引号后面加一个空格(或两个):

aList = [
   'one'  ,
   'two'  ,
   'three'
   'four'  ,
]

现在更明显的是'three'缺少它的尾随逗号

建议:我建议python有一个pragma,表示在某个区域中禁止字符串-文字串联:

^{pr2}$

默认情况下允许连接(以保持兼容性)

还有一条线索:

https://groups.google.com/forum/#!topic/python-ideas/jP1YtlyJqxs%5B1-25%5D

有趣的问题,我只是玩了一下,因为没有答案,所以我发布了我的解决方案:

#!/usr/bin/python

import tokenize
import token
import sys

with open(sys.argv[1], 'rU') as f:
    toks = list(tokenize.generate_tokens(f.readline))
    for i in xrange(len(toks) - 1):
        tok = toks[i]
        # print tok
        tok2 = toks[i + 1]
        if tok[0] == token.STRING and tok[0] == tok2[0]:
            print "implicit concatenation in line " \
                "{} between {} and {}".format(tok[2][0], tok[1], tok2[1])

你可以给程序提供它自己,结果应该是

^{pr2}$

相关问题 更多 >

    热门问题