Say we have a simple python function with the signature:
def foo(first, second, third=50)
When I call it from my main
, I will always have the first and second parameters, but I don't always have the third.
When I try to get the third from a dictionary I used: third = dict['value'] if 'value' in dict.keys() else None
The problem is that when I pass this None
I want the function to use its default third parameter and be 50, but it just uses None
. I also tried it with []
.
Is there a more elegant way to do this, except for calling the function twice, depends if third
exists, one time with it and one time without it, as follows?
third = dict['value'] if 'value' in dict.keys() else None
if third:
foo(first, second, third)
else:
foo(first, second)
You could do:
kwargs = {'third': dict['value']} if 'value' in dict else {}
foo(first, second, **kwargs)
The first line creates a kwargs
dictionary which only contain a key third
if there's value
in dict
, otherwise it's empty. And while calling the function, you can just spread that kwargs
dictionary.