3

A similar question has been asked before but I don't know that I like the answer. You have a parent function, which calls a child function.

def parent(a):
   return child(a) * 2

def child(a, b=10, c=20):
   return a + b + c

If I want the parent method to expose b and c, I can do something like below. It works, but seems cumbersome, as I'm reaching for it a lot (maybe that suggests some other problem).

def parent(a, b=None, c=None):

    kwargs = {}
    if b is not None:
        kwargs['b']=b
    if c is not None:
        kwargs['c']=c

    return child(a, **kwargs)

Is there a better (i.e. less code) way to do this?

7
  • 1
    Where was it asked before? Place a bounty on that question asking for new answers. Commented Jan 16, 2019 at 20:05
  • Why don't you set the default values for b and c in parent() to the default values of b and c in child()? Then you can just call child(a=a, b=b, c=c). Commented Jan 16, 2019 at 20:08
  • I may be mistaken but right now isn't parent identical to child? parent = child has the exact same functionality? Commented Jan 16, 2019 at 20:08
  • @9769953 child was defined earlier. the defaults for child make sense. what if other methods want to call child? I want them to also have access to those sensible defaults Commented Jan 16, 2019 at 20:10
  • seems that this isn't a duplicate after all. OP is aware of the solutions, and it looks not that good. Besides the question is more generic and understandable Commented Jan 16, 2019 at 20:11

1 Answer 1

3

If parent and child are both your own functions, then you could have the default values defined as a constant that is shared for both functions.

B_DEF = 10
C_DEF = 20

def parent(a, b=B_DEF, c=C_DEF):
   return child(a,b,c) * 2

def child(a, b=B_DEF, c=C_DEF):
   return a + b + c
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.