0

Is there a way to call a function with an argument but have the argument in a way that the default value of the function is used instead? Like

def f(val="hello"):
    print(val)

def g(a=Undefined):  #replace Undefined with something else
    f(a)

>>> g()
hello

The reason is, the called function is not under my control and I want to inherit its default value. Of course I could

def h(a=None):
    f(a) if a else f()

or even

def k(a=None):
    j = lambda  : f(a) if a else f()
    j()

since I have to call that function a few times and also pass other parameters. But all that would be much easier if I could just tell the function I want to use its default value.

I could also simply copy paste the default value to my function, but don't want to update my function if the other one changes.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Mathias
  • 1,470
  • 10
  • 20
  • I think the most readable and maintainable option is your second code. Something along the lines of: `if a is None: f() else: f(a)` – Tomerikoo Aug 03 '21 at 09:24
  • TL;DR: No, if you pass an argument, then that value *will* be used, regardless of what value it is. There's no "use default value" value. You can only elect to *not* pass that argument, meaning you might need to filter out kwargs dynamically on your calling side: `f(**({a: a} if a else {}))`. You could also inspect the function's signature and explicitly take its default value, for example. – deceze Aug 03 '21 at 09:26
  • Yeah thanks I kinda didn't believe there was. Thanks @Konrad-rudolph for linking the other answers. I didn't find them myself. – Mathias Aug 03 '21 at 09:32
  • @Mathias That was deceze, not me :) – Konrad Rudolph Aug 03 '21 at 10:05

0 Answers0