0

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.)

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.