Motmot
Motmot

Reputation: 121

Using one function as an optional argument in another function

Say I've got this function (a very simple function just to get my point across):

def f(x):
    if x:
         return(True)
    return(False)

Now I want to use this function as an optional argument in another function, e.g. I tried something like this:

def g(x, f_out = f(x)):
    return(f_out)

So basically if I did g(1) the output should be True, and if I did g(0) I want the output to be False, as f(0) is False and thus f_out is False.

When I try this though, f_out is always True regardless of x. How can I make it such that the function f is actually called when getting the value f_out?

The code that I'm actually using this principle on is obviously more complicated but it's the same idea; I have an optional argument in some function1 that calls a different function2 with parameters which are already parameters in function1, e.g. x in my example. (Sorry I'm aware that's perhaps an unclear way of explaining.)

Upvotes: 0

Views: 125

Answers (2)

mhawke
mhawke

Reputation: 87064

f_out = f(x) attempts to call f() at the time that the function is declared (which fails without a global x defined), not when it is invoked. Try this instead:

def g(x, f_out=f):
    return f_out(x)

This calls f() with argument x and returns its value from g().

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599490

You're calling the function f_out in the declaration. You want to pass the function itself as a parameter, and call it inside g:

def g(x, f_out=f):
    return f_out(x)

Upvotes: 3

Related Questions