Skip to content

Potential Asynchronous Context Confusion in set_headers #37

@nitish-yaddala

Description

@nitish-yaddala

Description

In the set_headers method, the code tries to detect if set_header is a coroutine using inspect.iscoroutinefunction and raises a RuntimeError if it detects an asynchronous function.

However, this behavior may confuse developers because:

  • It does not offer a fallback mechanism (such as awaiting automatically if possible).
  • The error message does not suggest a clear next step, such as using the set_headers_async method instead.

This could lead to confusion or misuse, especially in frameworks that rely heavily on asynchronous responses (e.g., FastAPI).

Affected Code

if inspect.iscoroutinefunction(set_header):
    raise RuntimeError(
        "Encountered asynchronous 'set_header' in synchronous context."
    )

Lines 242–245

Recommendation

  • Improve the RuntimeError message to clearly advise the developer to use set_headers_async instead.
  • Optionally enhance the logic to auto-detect an active asynchronous context and automatically handle it, for example:
    • Check if an event loop is running using asyncio.get_running_loop().
    • If yes, optionally raise a different, more helpful exception or adapt behavior accordingly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions