0

I would like to be able to wrap a function, while still allowing optional (keyword) arguments in the outer function. I can do this:

def outer(p1, p2, *a, **k):
     inner(*a, **k)

but what if I want for p2 to be an "optional argument"? Obviously:

def outer(p1, p2=None, *a, **k):
     inner(*a, **k)

won't work, and I know why it won't work. I'm wondering if there's a nice, clean way to achieve this. Is there some well-known pattern or convention?

Captain Midday
  • 659
  • 8
  • 18

2 Answers2

1

Use the functools module:

outer2 = functools.partial(outer, p2=None)
mguijarr
  • 7,641
  • 6
  • 45
  • 72
1

If you just want to ensure that p2 is present when the arguments are passed from outer to inner:

 def outer(p1, *a, **k):
     if 'p2' not in k: k.update(p2 = None)
     inner(*a, **k)

for a more general way you can keep a dict of defaults and apply them when needed:

def outer (p1, *args, **kwargs):
    defaults = {'a': 1, 'b':2}
    for k, v in defaults.items():
        if k not in kwargs: kwargs[k] = v
    inner(*a, **k)

If that's the case you might want to edit the title of your post to something along the lines of 'how to include default values in **kwargs arguments' since the wrapping is not really part of the syntax

theodox
  • 12,028
  • 3
  • 23
  • 36