Calling a Python function with *args,**kwargs and optional / default arguments

后端 未结 4 1556
情深已故
情深已故 2020-11-27 14:06

In python, I can define a function as follows:

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

In this case, i can call func as:



        
4条回答
  •  天涯浪人
    2020-11-27 14:40

    You can do that in Python 3.

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

    The bare * is only used when you want to specify keyword only arguments without accepting a variable number of positional arguments with *args. You don't use two *s.

    To quote from the grammar, in Python 2, you have

    parameter_list ::=  (defparameter ",")*
                        (  "*" identifier [, "**" identifier]
                        | "**" identifier
                        | defparameter [","] )
    

    while in Python 3, you have

    parameter_list ::=  (defparameter ",")*
                        (  "*" [parameter] ("," defparameter)*
                        [, "**" parameter]
                        | "**" parameter
                        | defparameter [","] )
    

    which includes a provision for additional parameters after the * parameter.

    UPDATE:

    Latest Python 3 documentation here.

提交回复
热议问题