[英]Unintentional trailing comma that creates a tuple
在 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
已經將此檢測為一個問題(從版本 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
,例如在the_only_elem, = our_list
。)另一種選擇是編寫自己的簡單line.rstrip().endswith(',') and '=' in line
來檢查line.rstrip().endswith(',') and '=' in line
(第二項檢查是在某種程度上允許多行列表聲明)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.