You would use kwargs
and do the assignment in the call not the definition:
def foo2(*args, **kwargs): # kwargs takes our key/values arguments
print args, kwargs
foo2(1, 2, 3, bar="foo") # bar is assigned to in call when using kwargs
Which gives:
(1, 2, 3) {'bar': 'foo'}
You could use get
to set foo
as a default for bar
like so:
def foo2(*args, **kwargs):
kwargs["bar"] = kwargs.get("bar", "foo") # if bar is not set use foo as val
print args, kwargs
foo2(1, 2, 3, bar="foo")
foo2(1, 2, 3, bar="notfoo")
foo2(1, 2, 3)
So that kwargs["bar"]
is always foo
unless explicitly changed:
(1, 2, 3) {'bar': 'foo'}
(1, 2, 3) {'bar': 'notboo'}
(1, 2, 3) {'bar': 'foo'}