Function Parameters

Ian Kelly ian.g.kelly at gmail.com
Thu Dec 27 16:01:19 EST 2012


On Thu, Dec 27, 2012 at 1:47 PM, Joseph L. Casale
<jcasale at activenetwerx.com> wrote:
>> Don't use kwargs for this.  List out the arguments in the function
>> spec and give the optional ones reasonable defaults.
>
>> I only use kwargs myself when the set of possible arguments is dynamic
>> or unknown.
>
> Gotch ya, but when the inputs to some keywords are similar, if the function is called
> with two of three (which is valid) and the arg name isn't used, the assignment is order
> dependent and arbitrary in a sense and I can not distinguish.

But the caller knows the order of the arguments, so if they just pass
two arguments positionally, then presumably those first two arguments
are the ones that they intend.

> It would be nice if you could force the keyword to be mandatory to forgo the assumption
> in assignment like kwargs provides with gets. I suppose all the time wasted here is in vain
> as the caller could blunder elsewhere...

In Python 3 you can designate arguments as keyword-only by placing
them after the * argument:

def example(self, *args, keyword1, keyword2=None):
    # Takes one or more positional arguments.
    # Required argument keyword1 and optional argument keyword2
    # can only be passed by keyword.
    pass

def example2(self, *, keyword='foo'):
    # Takes exactly one positional argument.
    # Optional argument keyword can only be passed by keyword.
    pass



More information about the Python-list mailing list