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.

4
  • 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) Commented Aug 3, 2021 at 9: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. Commented Aug 3, 2021 at 9:26
  • Yeah thanks I kinda didn't believe there was. Thanks @Konrad-rudolph for linking the other answers. I didn't find them myself. Commented Aug 3, 2021 at 9:32
  • @Mathias That was deceze, not me :) Commented Aug 3, 2021 at 10:05

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.