Python async context manager needs to raise exception to caller

Viewed 311

I have an context manager that is used like this:

async with await MyContextManager() as cm:
    # cm is now doing heavy processing in the background until
    # it's told to stop...
    await asyncio.sleep(1)  # simulate doing other things while
                            # cm continues to process
    # more processing
    await cm.change_behavior()
    # cm is now has even more work that it's processing...
    while True:
        await asyncio.sleep(1)
        # cm just continues until it's told to stop, so this
        # loop ensures it never stops

If MyContextManager.change_behavior() throws an exception, all is good, the caller can catch it or ignore it or whatever. But what if the context manager needs to raise an exception during the calling block's sleep()? In other words, if it's a long-lived background process that encounters an error condition, how do I notify the with block of the exception?

Bigger picture

The context manager in this case is basically a communication controller. Messages are being received and sent, etc. The calling process mostly only cares that the context manager is doing its thing but will also occasionally send messages to the CM to alter the state of communications. What I need is the ability to know the context manager is running successfully or to exit the code block if something goes wrong.

0 Answers
Related