5

In the code I'm viewing, I saw some class method like this:

class A(B):

    def method1(self,):
        do_something

    def method2(self,):
        do_something_else

Why the writer leave a comma behind self, what's his/her purpose?

Zen
  • 4,381
  • 5
  • 29
  • 56

1 Answers1

5

syntatically, the trailing comma is allowed but doesn't really mean anything. This is pretty much just a stylistic preference. I think that most python programmers would leave it off (which is the advice that I would also give) but a few might prefer it to make it so that it's easy to add more arguments later.

You can also keep it in there when calling the function. You'll see this more often with functions which take lots of default arguments:

x = foo(
    arg1=whatever,
    arg2=something,
    arg3=blatzimuffin,
)

This works for lists and tuples too:

lst = [x, y, z,]
tup = (x, y, z)
tup = x,  # Don't even need parens for a tuple...

It's particularly nice if you want to format nested stuff nicely:

{
    "top": [
        "foo",
        "bar",
        "baz",
    ],
    "bottom": [
        "qux",
    ],
}

As when adding things to the list you just need to add/edit 1 line, not 2.

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • it's wired that some of his method has that comma, and some doesn't, it seems that he is intend to do so. – Zen Apr 22 '14 at 03:06
  • 1
    I would definitely leave it off. Cf. [Trailing commas in python tuples.](http://stackoverflow.com/questions/11597901/trailing-comma-in-list-not-invalid-syntax) – fr1tz Apr 22 '14 at 03:07
  • @Zen -- It's not that weird. People are unfortunately inconsistent all the time ... Programmers aren't exempt :-) – mgilson Apr 22 '14 at 03:10
  • "Easy" as in, doesn't have to check whether a comma needs to be added or not? I've seen similar things done in Ruby and the reason was also because it's "easier" but I never asked what was easier about it. – MxLDevs Apr 22 '14 at 03:10
  • @MxyL -- It's one less character to type. Again, I don't recommend this for function definitions. formatted lists/tuples/dicts which span multiple lines can be kinda nice. – mgilson Apr 22 '14 at 03:12
  • yes just do not ask internet explorer about a trailing comma in js :D – sherpya Apr 22 '14 at 03:19
  • @sherpya -- Well, to be fair, that's a completely different language and AFAIK, the trailing comma isn't part of the ECMA script specification ... – mgilson Apr 22 '14 at 04:17
  • yes a bit off topic and you are right but every other browser on earth is happy with trailing comma, except ie :) – sherpya Apr 22 '14 at 04:35