Should I add a trailing comma after the last argument in a function call?

前端 未结 5 903
慢半拍i
慢半拍i 2020-12-15 16:15

What is better to do?

self.call(1, True, \"hi\")

or

self.call(1, True, \"hi\",)

And what in the following

5条回答
  •  一个人的身影
    2020-12-15 16:30

    I think, in this matter the same reasons apply as for lists and tuples, because the function argument list is exactly that.

    Here's a quote from the FAQ on design decisions that were made for the language (c.f.):

    Why does Python allow commas at the end of lists and tuples?

    Python lets you add a trailing comma at the end of lists, tuples, and dictionaries:

    [1, 2, 3,]
    ('a', 'b', 'c',)
    d = {
        "A": [1, 5],
        "B": [6, 7],  # last trailing comma is optional but good style
    }
    

    There are several reasons to allow this.

    When you have a literal value for a list, tuple, or dictionary spread across multiple lines, it’s easier to add more elements because you don’t have to remember to add a comma to the previous line. The lines can also be reordered without creating a syntax error.

    Accidentally omitting the comma can lead to errors that are hard to diagnose. For example:

    x = [
      "fee",
      "fie"
      "foo",
      "fum"
    ]
    

    This list looks like it has four elements, but it actually contains three: “fee”, “fiefoo” and “fum”. Always adding the comma avoids this source of error.

    Allowing the trailing comma may also make programmatic code generation easier.

提交回复
热议问题