Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the usage to add a comma after self argument in a class method?

Tags:

python

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?

like image 789
Zen Avatar asked Apr 22 '14 02:04

Zen


1 Answers

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.

like image 51
mgilson Avatar answered Oct 18 '22 06:10

mgilson