user3225309
user3225309

Reputation: 1373

Python why "asyncio.exceptions.InvalidStateError: Exception is not set." here?

If you look at the code:

import asyncio
import datetime as dt


def get_results_or_none(tasks):
    results = []
    for task in tasks:
        if task.cancelled():
            print(task.get_name(), 'cancelled')
            results.append(None)
        else:
            if task.exception():
                print(task.get_name(), task.exception())
                results.append(None)
            else:
                print(task.get_name(), 'result', task.result())
                results.append(task.result())
    return results

async def main():

    tasks = [
        asyncio.create_task(asyncio.sleep(1), name='task1'),
        asyncio.create_task(asyncio.sleep(3), name='task2'),
    ]
    await asyncio.wait(tasks, timeout=2)

    return get_results_or_none(tasks)

start_time = dt.datetime.now()
task1, task2 = asyncio.run(main(), debug=True)

total_time = (dt.datetime.now() - start_time).total_seconds()
print('lasted', total_time)

print(task1)
print(task2)

You can see that task2 is intentionally too long and causes timeout. I hoped that it will be enough to just retrieve task.exception(), but I get an output like this one:

task1 result None
Traceback (most recent call last):
  File "/home/user/project/chk_invalid_state_error.py", line 31, in <module>
    task1, task2 = asyncio.run(main(), debug=True)
  File "/home/user/miniconda3/envs/algot/lib/python3.9/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/home/user/miniconda3/envs/algot/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
    return future.result()
  File "/home/user/project/chk_invalid_state_error.py", line 28, in main
    return get_results_or_none(tasks)
  File "/home/user/project/chk_invalid_state_error.py", line 12, in get_results_or_none
    if task.exception():
asyncio.exceptions.InvalidStateError: Exception is not set.

What does it mean "asyncio.exceptions.InvalidStateError: Exception is not set." in this case?

Upvotes: 1

Views: 8058

Answers (1)

jsbueno
jsbueno

Reputation: 110166

Thast error is raised if you check for exception in a task that is not done yet. (The call to .wait() timed out,but the task is still running).

You have to check if it is done, by calling the .done() method before calling .exception(): https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.exception

Upvotes: 4

Related Questions