无意后面的逗号,创建一个元组
在Python中,留下这样一个结尾逗号,当然,不是SyntaxError
:无意后面的逗号,创建一个元组
In [1]: x = 1 ,
In [2]: x
Out[2]: (1,)
In [3]: type(x)
Out[3]: tuple
但是,与此同时,如果后面的逗号被提意外,可能很难赶上这种“问题”,特别是对于Python新手来说。
我在想如果我们可以赶上这种“问题”,静态地,借助PyCharm
智能代码质量控制功能; mypy
,pylint
或flake8
静态代码分析工具。
或者,另一个想法是限制/突出显示创建一个项目元组隐式没有括号。可能吗?
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.
这不是一个无意的行为,因为元组运算符是,
而不是()
。这里括号的作用与算术表达式中的相同。所以你不能在Python解释器中限制这种创建,否则它会是其他语言。
我同意拖尾的逗号有时是无意的。像pylint
这样的Lint工具通常能够通过一般类型推断来捕捉这些错误(即他们看到你试图向一个数字添加一个元组)。 (另请注意,有时候尾随的逗号是有用的,并且不是无意的,例如在the_only_elem, = our_list
中。)另一种选择是编写自己的简单的短语,检查line.rstrip().endswith(',') and '=' in line
(第二个检查是否允许多行列表声明)。
你的linter checker会产生很多误报(至少在我的代码中):'data = func(param1,\ n param2 ...)' – MariusSiuram
@MariusSiuram答案中没有我的“linter checker”,只是一个插图。我提到它不完美。 –
@onlynone顺便说一句,我不知道你的第一个问题/语句的意思。我应该多加一个“这可能吗?”到问题的第一部分?我认为这很清楚我的意思,但是让我知道是否有任何可以改进的问题来使问题更加清晰。谢谢。 – alecxe
我想这很好。这只是奇怪的措辞:“是否有可能(用静态代码分析来检测这个问题)”是一种明显的“是!”! - 这正是静态代码分析工具所做的。它变成了python中最流行的一个,你提到自己的一个,完全是你想要的。另一种解释是“是否有可能(限制创建一个没有parens的项目元组)”,似乎是一个明显的“否”,因为它只是python的工作方式。 – onlynone
PEP8异常含糊地描述了尾随逗号的用法:“好,但令人困惑:”我期待更权威的指导https://www.python.org/dev/peps/pep-0008/#when-to-use-尾随逗号 –