Skip to content

asyncio.timeout accepts NaN, causing strange behaviour #163101

Backlog

Description

@hu-jeff

Bug report

NaN handling is unspecified in the docs but the way it's handled is inconsistent with other asyncio functions (asyncio.sleep).

We can create some weird situations when passing NaN in asyncio.timeout like delaying unrelated timers, aborting an idle loop or cancelling unrelated tasks under asyncio.run.

Should asyncio.timeout reject NaN consistent with asyncio.sleep?

Ex. NaN timeout causes asyncio.run to raise

import asyncio

async def worker():
    try:
        await asyncio.Event().wait()
    except asyncio.CancelledError:
        print("worker cancelled")
        raise

async def bad():
    async with asyncio.timeout(float("nan")):
        await asyncio.Event().wait()

async def main():
    await asyncio.gather(worker(), bad())

asyncio.run(main())

CPython versions tested on:

3.15, 3.16, 3.14

Operating systems tested on:

macOS

Linked PRs

Activity

  1. added
    type-bug
    on Dec 3, 2026
  2. added
    stdlib
    on Dec 3, 2026
  3. asvetlov commented on Dec 3, 2026

    @asvetlov
    Contributor

    I guess yes, NaN argument should be rejected by both asyncio.timeout() and loop.call_later(), as we do it already for asyncio.sleep() after #105641

  4. picnixz commented on Dec 3, 2026

    @picnixz
    Member

    Personally I see that as a GIGO case where rejecting NaNs seems even an overkill but yeah we can remain consistent.

  5. hu-jeff commented on Dec 4, 2026

    @hu-jeff
    ContributorAuthor

    Thanks @asvetlov and @picnixz!

    Should I also make my fix cover asyncio.timeout_at and Timeout.reschedule? They seem like natural extensions.

    Also, definitely see the GIGO point. What makes NaN worth rejecting for me aside from consistency, is that one task's bad input can affect unrelated tasks that supplied valid inputs.

  6. picnixz commented on Dec 4, 2026

    @picnixz
    Member

    I think so, and various init constructors. More generally everywhere where it makes sense i think

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibtopic-asynciotype-bug

    Projects

    • Status
      Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions