What is the syntax rule for having trailing commas in tuple definitions?

前端 未结 10 1469
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 05:54

In the case of a single element tuple, the trailing comma is required.

a = (\'foo\',)

What about a tuple with multiple elements? It seems t

10条回答
  •  终归单人心
    2020-11-22 06:30

    In all cases except the empty tuple the comma is the important thing. Parentheses are only required when required for other syntactic reasons: to distinguish a tuple from a set of function arguments, operator precedence, or to allow line breaks.

    The trailing comma for tuples, lists, or function arguments is good style especially when you have a long initialisation that is split over multiple lines. If you always include a trailing comma then you won't add another line to the end expecting to add another element and instead just creating a valid expression:

    a = [
       "a",
       "b"
       "c"
    ]
    

    Assuming that started as a 2 element list that was later extended it has gone wrong in a perhaps not immediately obvious way. Always include the trailing comma and you avoid that trap.

提交回复
热议问题