Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 best practice argument order

Tags:

python

In this question it is described that since Python3 you can use this notation:

def func(a, b, *args, kw1=None, **kwargs)

to define a function, instead of traditional Python2 way:

def func(a, b, kw1=None, *args, **kwargs)

Is there any agreed best practice which signature should be used or is it based on personal preference?

like image 777
PKuhn Avatar asked Jul 03 '16 12:07

PKuhn


1 Answers

There cannot be any "best" practice here, since those two definitions mean different (in a way, the opposite) things:

def func(a, b, kw1=None, *args, **kwargs):
    ...

means that the function will have an optional named argument kw1, which can be passed either as a keyword (func(1, 2, kw1=3)) or as an positional argument (func(1, 2, 3)). (In fact, unless specified explicitly with relatively new /-syntax, any named argument can be passed as a keyword.)

However, if a named arguments follows *args (or just *), it may be passed only as a keyword. For example:

def func(a, b, *, kw1=None, **kwargs):
    ...

cannot be called as func(1, 2, 3), and having

def func(a, b, *args, kw1=None, **kwargs):
    print(a, b, kw1)

func(1, 2, 3) will print 1, 2, None, because the positional argument goes to the *args part. (Thanks @tobias_k for pointing that out).

like image 56
bereal Avatar answered Oct 25 '22 07:10

bereal