I need to do something like this:
def func1(a, *args, b="BBB", **kwargs):
print "a=%s b=%s args=%s kwargs=%s" % (a, b, args, kwargs)
So that calling like this:
func1("AAAA", h="HHH", j="JJJ")
Produces the output:
a=AAAA b=BBB args=() kwargs={'h': 'HHH', 'j': 'JJJ'}
But it is not possible to put a default named argument after *args
. (SyntaxError: invalid syntax
)
- Why is this not allowed?
- Is there any readable way to implement this? The only way I know is
b=kwargs.pop("b", "BBB")
, but this is not very readable. I would prefer to have this in the function call definition, where it belongs: it is a parameter which will always have a value, either a default value or a user-given value.
EDIT
I could put b
in front of args
:
def func1(a, b="BBB", *args, **kwargs):
print "a=%s b=%s args=%s kwargs=%s" % (a, b, args, kwargs)
But that would mean that this call:
func1("AAAA", "CCC", h="HHH", j="JJJ")
Assigns "CCC"
to b
, which I do not want. I want b
to be a named arg, not a possitional arg.