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

What is better to do?

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

or

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

And what in the following cases:

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

or

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

?

Reasons for adding a trailing comma in data structures are familiar to me, but what about function calls?


Solution 1:

I think there's no technical reason to avoid trailing commas in function calls, but some people probably do find them distracting. Some may stop and say:

"Hmmm, I wonder if that's really supposed to be there?"

I hesitate to call this a benefit, but one effect of using trailing commas in conjunction with an indented style is to make version control diffs look a little bit cleaner when adding an argument.

For example, a function like this:

def my_fun(a, b, c=None):
    ...

...called like this:

my_fun(
    a='abc',
    b=123
)

...then changed to this:

my_fun(
    a='abc',
    b=123,
    c='def'
)

produces this diff in git:

$ git diff
...
 my_fun(
     a='abc',
-    b=123
+    b=123,
+    c='def'
 )

Whereas,

my_fun(
    a='abc',
    b=123,
)

changed to...

my_fun(
    a='abc',
    b=123,
    c='def',
)

produces this diff in git:

$ git diff
...
 my_fun(
     a='abc',
     b=123,
+    c='def',
 )

Solution 2:

I'll also leave my 2 cents here, even if this thread has been here for quite some time, it might benefit somebody :)

PEP8 actually does say when to use trailing commas and if you follow their recommendations (not mandatory, but definitely recommended) then the second one-liner example of yours can be ruled out, i.e:

No:

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

Yes:

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

Usages in function calls (use sparingly to never) and here's why:


  • One of the coding principles is that a function should do one thing, and one thing only. So, seeing a trailing comma there, a lot of questions may arise, when they really shouldn't. Normally when you see a trailing comma somewhere, you expect that thing to change over time. So if it's a list, tuple, dict, etc. it usually indicates that whoever designed it, did it with the intention of physically adding or removing or switching lines in that data structure, and well... you don't see that with functions very often, or at least you shouldn't, and if you do, a better design should be considered.

  • As aforementioned, a function should also be very predictable, you don't design a function that sends mail and rockets to the moon at the same time, and leave a trailing comma when calling it to send mail because who knows when you might send rockets and you want less cluttered diff (it will only cause more confusion and its a poor design).

  • An arbitrary number of parameters (or even a fixed, but large number of parameters) usually indicates that either you are either instantiating an object there, or you are doing multiple things, when really what you should be doing is split your design into creating multiple smaller functions, that each do one thing, hence, no trailing comma needed.

  • Also consider, even if you did have a function, which you would be able to call with multiple number of parameters, think about how often would you do that and what it implies? Well that would imply something like:

    • Refactoring the code at the call place (which may be in another function, or in a module or somewhere) because usually the result from functions is stored in variables, and you need to use that new result, so that would imply refactoring.
    • If it doesn't imply refactoring then it means the function doesn't return anything, or it returns the same thing, in which case it means that it does multiple things with the extra arguments passed in the call, which, as previously said, is not very ideal.

Actual usages


  • Trailing commas make sense, like you said in data structures, data structures that are expected to change physically over time, because if you change it at run-time, well it wouldn't make any sense for anything that's in the editor, except for the definition which might as well be an empty structure [] xD

  • Where data structures (lists, dicts, sets, tuples, etc) are expected to change (physically, the source code) then trailing commas are actually recommended and actually useful (see the full PEP link, it has use cases and recommendations)

Conclusion:


  • Recommended in multi-line data structures that are expected to physically change
  • Rarely to never in function calls
  • Never in function definitions

Solution 3:

In data structures, the trailing comma is "useful" for making it easier to add items:

a = [
      1,
      2,
      3,
    ]

is easier to change into

a = [
      1,
      2,
      3,
      4,
      5,
    ]

because you don't have to edit the line that says 3,.

But there is no such benefit in function calls which usually don't change in length. So I would discourage the use of a trailing comma.

Solution 4:

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.

Solution 5:

This is tool specific, but it actually makes code refactoring much easier in vim/Gvim even on single line function parameter lists.

def foo( a, b, c, e, d, ):

changed to

def foo( a, b, c, d, e, ):

When using vim, you can just delete the "e," or "d," with two keystrokes (dW) move to where you want to paste it in and press (p).

If you didn't have the ending comma, you end up having to remove it from your new last item and adding it to your old last item. Alternately, you'd have to be more careful deleting only up until the comma and pasting more precisely. With comma's everywhere, you can treat everything as uniform chunks that can be swapped around with ease.

Vim's apparently quite popular with python writers so this actually appears to have some merit: https://www.sitepoint.com/which-code-editors-do-pythonists-use/