无意的尾随逗号,创建一个元组

时间:2017-06-22 13:33:59

标签: python pycharm pylint static-code-analysis flake8

在Python中,留下这样的尾随逗号当然不是SyntaxError

In [1]: x = 1 ,

In [2]: x
Out[2]: (1,)

In [3]: type(x)
Out[3]: tuple

但是,与此同时,如果尾随逗号意外地 ,则可能很难捕捉到这种“问题”,特别是对于Python新手。

我在想,如果我们能够在PyCharm智能代码质量控制功能的帮助下,静态地早期发现这种“问题”; mypypylintflake8静态代码分析工具。

或者,另一个想法是限制/突出显示一个项目元组隐式没有括号。有可能吗?

2 个答案:

答案 0 :(得分:15)

pylint已将此问题视为问题(as of version 1.7)。

例如,这是tuple.py

"""Module docstring to satisfy pylint"""

def main():
    """The main function"""
    thing = 1,
    print(type(thing))

if __name__ == "__main__":
    main()
$ pylint tuple.py
No config file found, using default configuration
************* Module tuple
R:  5, 0: Disallow trailing comma tuple (trailing-comma-tuple)

------------------------------------------------------------------
Your code has been rated at 8.00/10 (previous run: 8.00/10, +0.00)

$ pylint --help-msg trailing-comma-tuple
No config file found, using default configuration
:trailing-comma-tuple (R1707): *Disallow trailing comma tuple*
  In Python, a tuple is actually created by the comma symbol, not by the
  parentheses. Unfortunately, one can actually create a tuple by misplacing a
  trailing comma, which can lead to potential weird bugs in your code. You
  should always use parentheses explicitly for creating a tuple. This message
  belongs to the refactoring checker. It can't be emitted when using Python <
  3.0.

答案 1 :(得分:0)

由于元组运算符为,而不是(),因此它不是非预期的行为。括号的作用与算术表达式中的作用相同。因此,您不能在Python解释器中限制此类创建,否则它将是其他语言。

我同意尾随的逗号有时是无意的。像pylint这样的Lint工具通常能够通过一般类型推断来捕获这些错误(即他们看到你试图将一个元组添加到一个数字)。 (另请注意,有时尾随逗号是有用的,而且不是无意的,例如在the_only_elem, = our_list中。)另一个选择是编写自己的简单linter来检查line.rstrip().endswith(',') and '=' in line之类的东西(第二个检查是允许多个行列表声明在某种程度上)。