Chris Nguyen
Chris Nguyen

Reputation: 160

How to tell if a function will be returning a value to a variable?

So to give as an example, imagine a function that computes a value and will either return the value to the variable or print it if it will not be stored into a variable such as:

def add(a, b):
    c = a+b
    if called: return c    ## Put the value into "answer" below
    else: print "Your answer is: ", str(c)    ## just print it

answer = add(10, 15)
print answer
## Should print 25

add(10, 20)
## Should print """Your answer is 30"""

I want to use this in various functions such as a UI or a generator but can't find a way to implement a Boolean statement to determine this.

I Googled this, and the only thing i found close was determining if the function was called or recursed(?). I just want the function to know if it should return the value to the variable or simply print it. Any ideas?

Upvotes: 0

Views: 73

Answers (1)

trincot
trincot

Reputation: 350242

A python function has no information on whether it's return value is being assigned or ignored. So, what you want is not possible.

If you are willing to make some design changes, you could add a parameter:

def add(a, b, print_it):
    c = a+b
    if print_it: print "Your answer is: ", str(c)    ## just print it
    else: return c    ## Put the value into "answer" below

answer = add(10, 15)
print answer
## Will print 25

add(10, 20, true)
## Will print """Your answer is 30"""

Or you could define a wrapper function specifically for printing the result:

def add(a, b):
    c = a+b
    return c

def print_add(a, b):
    print "Your answer is: ", str(add(a, b))    ## print add's return value

answer = add(10, 15)
print answer
## Will print 25

print_add(10, 20)
## Will print """Your answer is 30"""

You could make the second solution more generic by passing the base function to the wrapper function:

def add(a, b):
    c = a+b
    return c

def sub(a, b):
    c = a-b
    return c

def print_result(fn, a, b):
    print "Your answer is: ", str(fn(a, b))    ## print function's return value

answer = add(10, 15)
print answer
## Will print 25

print_result(add, 10, 20)
## Will print """Your answer is 30"""

print_result(sub, 10, 20)
## Will print """Your answer is -10"""

etc, etc.

Upvotes: 1

Related Questions