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?
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)
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module