Created
November 23, 2021 22:59
-
-
Save TFlexSoom/485595a3d2fb7bbc5ac2e75196e46b31 to your computer and use it in GitHub Desktop.
Try Finally Testing With Asynchronous and Synchronous Generators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import time | |
| import logging | |
| import asyncio | |
| def get_generator(): | |
| try: | |
| yield "hello there!" | |
| finally: | |
| logging.info("Finally Block Has Been Run!") | |
| async def get_generator_async(): | |
| try: | |
| await asyncio.sleep(1) | |
| yield "hello there!" | |
| finally: | |
| logging.info("Finally Block Has Been Run!") | |
| async def use_gen_and_exit(): | |
| var = await get_generator_async().asend(None) | |
| logging.info("printing Var!") | |
| logging.info(var) | |
| logging.info("Done printing Var!") | |
| time.sleep(1) | |
| logging.info("exitting") | |
| async def use_gen_and_wait_and_exit(): | |
| var = await get_generator_async().asend(None) | |
| time.sleep(1) | |
| logging.info("printing Var!") | |
| logging.info(var) | |
| logging.info("Done printing Var!") | |
| time.sleep(1) | |
| logging.info("exitting") | |
| async def use_gen_inner_and_cough(): | |
| logging.info("Entering Inner Loop") | |
| await use_gen_and_exit() | |
| logging.info("Exiting Outter Loop") | |
| def main(): | |
| format = "%(asctime)s: %(message)s" | |
| logging.basicConfig(format=format, level=logging.INFO, | |
| datefmt="%H:%M:%S") | |
| gen = get_generator() | |
| var = next(gen) | |
| logging.info(var) | |
| logging.info("Moving on to other calls") | |
| asyncio.run(use_gen_and_exit()) | |
| asyncio.run(use_gen_and_wait_and_exit()) | |
| asyncio.run(use_gen_inner_and_cough()) | |
| if __name__ == "__main__": | |
| main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment