【问题标题】:Unintentional trailing comma that creates a tuple创建元组的无意尾随逗号
【发布时间】:2017-11-25 19:47:38
【问题描述】:

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

In [1]: x = 1 ,

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

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

但同时,如果尾随的逗号不小心放了,可能很难捕捉到这种“问题”,尤其是对于 Python 新手而言。

我在想我们是否可以在PyCharm 智能代码质量控制功能的帮助下及早发现这种“问题”; mypy、pylint 或flake8 静态代码分析工具。

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

【问题讨论】:

  • @onlynone 顺便说一句,我不确定你的第一个问题/陈述是什么意思。我应该多写一个“有可能吗?”到问题的第一部分?我认为我的意思很清楚,但请告诉我是否有任何可以改进的地方以使问题更清晰。谢谢。
  • 我想这很好。只是奇怪的措辞:“有可能(通过静态代码分析检测这个问题)”是一种明显的“是的!” -- 这正是静态代码分析工具所做的。事实证明,python 最受欢迎的一种,你自己提到的一种,正是你想要的。另一种解释,“是否有可能(限制创建一个没有括号的项目元组)”,似乎是一个明显的“不”,因为这正是 python 的工作方式。
  • PEP8 异常模糊地将尾随逗号的这种使用描述为“好的,但令人困惑:”我希望得到更权威的指导 python.org/dev/peps/pep-0008/#when-to-use-trailing-commas
  • 尾随逗号没有任何“隐含”意义;明确记录了逗号是构成元组的原因,而不是括号,因此1, 非常明确。是的,静态分析可以帮助您找到创建单元素元组的情况。
  • @MartijnPieters 好吧,当然,我们可以称之为不那么明确:) 谢谢。

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


【解决方案1】:

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.

【讨论】:

    猜你喜欢
    • 2019-02-12
    • 2021-01-25
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 2018-01-10
    相关资源
    最近更新 更多