0

I have a outer function foo that calls two inner functions, bar1 and bar2. Each inner function (bar) has default parameters. I'd like to be able to call foo and specify whichever parameters I want, and then use the inner function defaults for whichever parameters I don't specify. How do I do this?

Example:

def foo(**kwargs):
    print(bar1(kwargs['b1p1'], kwargs['b1p2'])
          + bar2(kwargs['b2p1'], kwargs['b2p2']))

def bar1(b1p1 = '', b1p2 = ''):
    return str(b1p1+b1p2)

def bar2(b2p1 = 0, b2p2 = 0):
    return str(b2p1 * b2p2)

foo(b1p1 = 'a', b1p2='b', b2p1 = 1, b2p2 = 3) #returns ab3
foo(b1p1 = 'a') #should return  a0
foo() #should return 0
tmldwn
  • 435
  • 4
  • 13
  • 1
    You provide no information to the outer function so it's possible but painful to recreate positional arguments with the adequate values to call the inner functions. But it will be ugly and I don't see the sense. Why don't you work with named args in your outer function ? `def foo(*, b1p1='', b1p2='', b2p1=0, b2p2=0, **kwargs)` – 0x0fba Nov 30 '22 at 12:39
  • @0x0fba this is possible but it becomes unwieldy when the outer function calls a large number of parameterized functions, most of which will use the default parameters. E.g. I have a function that creates a figure with multiple subplots, and each subplot is generated by a function that has several default parameters that can be adjusted. I could paste the default parameters from all the inner functions into the outer function signature but that seems non-ideal. – tmldwn Nov 30 '22 at 12:48
  • 1
    I understand but at least you expose to the user the arguments he can use. The alternative is to have many conditions to recreate correctly each set of args for each inner function, that looks complicated, not readable nor maintainable. Hope you'll get answers with better alternatives. – 0x0fba Nov 30 '22 at 12:54

0 Answers0