The intent of the following code is for keyword arguments passed to main
to be passed on to the other called functions. However, if no value is given to main
for the key1
argument, then the default value of key1
in f2
is overridden by the value of None
passed by main
.
def main(x, key1=None, key2=None):
f1(x, key1=key1)
f2(x, key1=key1, key2=key2)
def f1(x, key1=None): # note key2 is absent
print(x, key1)
def f2(x, key1=42, key2=None):
print(x, key1, key2)
main(1)
Output:
(1, None)
(1, None, None)
Is there a simple way to change just the definition of main
(possibly including the arguments) so that the output of the called functions would be as below?
(1, None)
(1, 42, None)
Obviously, there are ridiculous ways to alter just main
to create that output, but it would be silly to insert logic into main
to pass the default value for a missing argument for a specific function, or to alter the keywords that are passed by main
depending on which of them is None
. So I'm not looking for a solution like that.
The usual way to get around this problem would be to use **kwargs
in all of the functions. Alternatively, you could change the definition of f2
:
def f2(x, key1=None, key2=None):
if key1 is None:
key1 = 42
print(x, key1, key2)
But I'm wondering if there's another option.