Exception has occurred: TimeoutError exception: no description

1.3k views Asked by At

I am specifically using python version 3.10 to run a websocket (or any long asyncio process) for a specified period of time which is covered in the python docs. The .wait_for() method looks like the correct solution.

I run this code (from the docs):

import asyncio

async def eternity():
    # Sleep for one hour
    await asyncio.sleep(3600)
    print('yay!')

async def main():
    # Wait for at most 1 second
    print('wait for at most 1 second...')
    try:
        await asyncio.wait_for(eternity(), timeout=1.0)
    except TimeoutError: 
        print('timeout!')


asyncio.run(main())

The docs are here: https://docs.python.org/3/library/asyncio-task.html?highlight=wait_for#asyncio.wait_for

However, I get the following error:

Exception has occurred: TimeoutError
exception: no description

...basically, the TimeoutError exception is not handled as expected.

My research shows that others have struggled with errors, for example here: Handling a timeout error in Python sockets

but the fixes are either aged (not relevant for 3.10) or do not work. I also notice that the docs specify this "Changed in version 3.10: Removed the loop parameter". So i am only interested in version 3.10 and above.

So I am wondering how to get the min reproducible example working or what i have done wrong please ?

2

There are 2 answers

7
Zz_GhostM4n_zZ On BEST ANSWER

You can remove the TimeoutError so it can jump down to the print('timeout') or can use this example to output the error

except Exception as exc:
    print(f'The exception: {exc!r}')
1
fancidev On

There are a number of TimeoutErrors in Python.

Replace except TimeoutError with except asyncio.TimeoutError and you’ll be good.

UPDATE with full example:

import asyncio

async def eternity():
    # Sleep for one hour
    await asyncio.sleep(3600)
    print('yay!')

async def main():
    # Wait for at most 1 second
    print('wait for at most 1 second...')
    try:
        await asyncio.wait_for(eternity(), timeout=1.0)
    except asyncio.TimeoutError: 
        print('timeout!')

asyncio.run(main())

Apparently the example in asyncio’s docs is wrong (or at least misleading). If you look at CPython’s source code, asyncio.TimeoutError is a different exception from TimeoutError up to Python 3.10, and was changed to an alias to TimeoutError in 3.11.