views:

18

answers:

1

I apologize if this question has already been asked/answered, I would have expected that to be the case but was unable to find any related questions...

I'd like to create a python function that takes two mandatory arguments, one named argument, and some unknown number of other, non-named arguments as so:

def my_function(arg1, arg2, arg3=None, *other_args):
    pass

Is this possible in Python 2.x?
Can a function accept named arguments in addition to a variable length argument list?

I believe the answer is 'no', in which case I'm thinking the only solution available to me would be something similar to the following:

def my_function(arg1, arg2, **kwargs):
    arg3 = kwargs["arg3"]
    other_args = kwargs["other_args"]

Is that correct?

A: 

That syntax is certainly valid, but I think you mean can you write the function signature such that arg3 is only bound if it's used as a named parameter (e.g. my_function(1, 2, arg3 = 3)), and otherwise to have all arguments past the first two be caught by *other_args, in which case the answer is no. Optional arguments can be specified by naming, but they're also positional like normal arguments and are filled in if enough parameters are available, before resorting to catch-alls like *args or **kwargs.

I would probably write it exactly as you did, using keyword arguments

Michael Mrozek