1

I have a function that has a return value. I'd like the function to behave differently when the return value of the function is assigned to something.

So something like this:

def func():
    if return_value_assigned():
         print("yes")
    else:
         print("no")
    return 0

# this should print "no"
func()

# this should print "yes"
a = func()

I've tried to use this method:

frame_stack = inspect.getouterframes(inspect.currentframe())
code_context = frame_stack[2].code_context[0]
is_return_value_assigned = re.match(r"[\w+ ,]*=", code_context) is not None

However, apparently, code_context only stores the last line of the function call. So for example, this wouldn't work:

a = func(*args, 
    **kwargs)

Is there a better way of doing this? Is it possible to get the code context of the entire function call instead of just the last line?

Astral Cai
  • 63
  • 7
  • I don't think it's possible. it may help if you explain what you are trying to achieve this way? – njzk2 Sep 02 '19 at 00:40
  • 2
    I can't think of a good reason why you would want to do this. It sounds like a horrible way of hitting side effect problems. "The code works, but I don't need the result, so I'll get rid of `a =`. Oh no, the code doesn't work anymore" – John3136 Sep 02 '19 at 00:43
  • 2
    No, the function runs _before_ you assign the return value to a variable, so there is no way for the function to know if it is going to be assigned to a variable in the future. You can parse the source code of the calling module, if the source is available, but I agree that this is a horrible, horrible way of doing whatever you are trying to accomplish. – Selcuk Sep 02 '19 at 01:05
  • 1
    What output would you want for things like `[func()]` or `foo(func())`? Both perform implicit assignments (the second one being less implicit than the first). – chepner Sep 02 '19 at 12:51

1 Answers1

1

The only option that makes any sense, with regards to every programming standard on caller vs. callee responsibilities I've ever seen, is something like this:

def foo(return_value=True):
    if return_value:
        print("yes")
    else:
        print("no")
    return 0

Otherwise you're asking the called function to extact information from the caller, which seems like a really bad idea for many reasons.

neutrino_logic
  • 1,289
  • 1
  • 6
  • 11