Ad

Python: How To Return Two Values At Different Position Of Calculating In A Function?

I want to have a function that process the data in the predefined pipeline, and I need the data at intermediate and final step, so I want to have a function that I can call twice, in the first call, the function returns the intermediate data, and in the second call, the function starts from the last return position and returns the final data, so something like this:

def tworeturns(x):
    intermediate = do-something(x)
    return intermediate
    final = do-something(intermediate)
    return final

How to implement this with python?

==========================================================================

Thanks to new-dev-123's answer I was able to return two values, but then I got another problem. After the first yield, I changed the intermediate, and when I call the next for the second time, I want the function to compute based on the modified intermediate, not the original intermediate. Is there a way of doing it?

Ad

Answer

Using a generator like a coroutine allows you to effectively pause the function and you can drive it using next()

>>> def tworeturns(x):
...     print(f"hi {x}")
...     yield
...     print(f"bye {x}")
...     yield
... 
>>> corou = tworeturns("bob")
>>> next(corou)
hi bob
>>> next(corou)
bye bob

here's a quick demo I did on cli

So for your example you would do something like:

def tworeturns(x):
    intermediate = do-something(x)
    yield intermediate
    final = do-something(intermediate)
    yield final

corou = tworeturns(x)
first_value = next(corou)
second_value = next(corou)
Ad
source: stackoverflow.com
Ad