Skip to content

Instantly share code, notes, and snippets.

@Taiiwo
Created October 8, 2019 16:02
Show Gist options
  • Select an option

  • Save Taiiwo/cb7ce8bea96ed82c23d5586ee0b08b1b to your computer and use it in GitHub Desktop.

Select an option

Save Taiiwo/cb7ce8bea96ed82c23d5586ee0b08b1b to your computer and use it in GitHub Desktop.

Revisions

  1. Taiiwo created this gist Oct 8, 2019.
    32 changes: 32 additions & 0 deletions halt.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    import asyncio

    loop = asyncio.get_event_loop()

    # returns true if coroutine function blocks or errors, else false
    async def holds(function, arg):
    # try block for catching errors
    try:
    # create a promise for the function to run in another thread
    p = loop.run_in_executor(None, await function, (arg,))
    # return if the coroutine takes more than 0.1 seconds to complete
    # by awaiting the above promise for 0.1 seconds, and returning true if
    # it didn't finish in time
    return await asyncio.wait([p], timeout=0.1)[1]
    except:
    # code errored, so return true
    return True

    async def weird(f):
    if await holds(f, f):
    while True:
    pass
    else:
    return

    async def main():
    # the beginning of the event loop
    print(await holds(weird, weird))

    if __name__ == "__main__":
    # put main() in the event loop, then wait until it's done
    loop.run_until_complete(main())