Python 3 best practice argument order

后端 未结 1 1000
猫巷女王i
猫巷女王i 2021-02-08 16:45

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,

1条回答
  •  情深已故
    2021-02-08 17:11

    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).

    0 讨论(0)
提交回复
热议问题