I have the following code:
def foo(func, *args, named_arg = None):
return func(*args)
returning a SyntaxError:
File "tester3.py", line 3
def foo(func, *args, named_arg = None):
^
Why is that? And is it possible to define somewhat a function in that way, which takes one argument (func), then a list of variable arguments args before named arguments? If not, what are my possibilities?
The catch-all
*argsparameter must come after any explicit arguments:If you also add the catch-all
**kwkeywords parameter to a definition, then that has to come after the*argsparameter:Mixing explicit keyword arguments and the catch-all
*argsargument does lead to unexpected behaviour; you cannot both use arbitrary positional arguments and explicitly name the keyword arguments you listed at the same time.Any extra positionals beyond
funcare first used fornamed_argwhich can also act as a positional argument:This is because the any second positional argument to
foo()will always be used fornamed_arg.In Python 3, the
*argsparameter can be placed before the keyword arguments, but that has a new meaning. Normally, keyword parameters can be specified in the call signature as positional arguments (e.g. call your function asfoo(somefunc, 'argument')would have'argument'assigned tonamed_arg). By placing*argsor a plain*in between the positional and the named arguments you exclude the named arguments from being used as positionals; callingfoo(somefunc, 'argument')would raise an exception instead.