Reputation: 58
For example if I have:
def foo(arg1, def_par="yes", *args,**kwargs):
print(arg1,def_par)
for key, value in kwargs.items():
print("{},{}".format(key,value))
for arg in args:
print(arg)
foo("Hello",1,2,smell="funky")
Then the interpreter outputs:
>>Hello 1
>>smell,funky
>>2
Is there a way to create an output where, unless explicitly defined by a keyword argument, the default argument is used to create an output such as:
>>Hello Yes
>>smell,funky
>>1
>>2
Upvotes: 1
Views: 77
Reputation: 106455
You can put variable positional arguments before keyword arguments:
Change:
def foo(arg1, def_par="yes", *args,**kwargs):
to:
def foo(arg1, *args, def_par="yes", **kwargs):
With this change, your code would output:
Hello yes
smell,funky
1
2
If for some reason you can't or don't want to change the function signature of foo
, you can obtain the default value of a parameter with inspect.signature
:
import inspect
foo("Hello", inspect.signature(foo).parameters['def_par'].default, 1, 2, smell="funky")
Upvotes: 2