Skip to content

Overload return type of recv #1578

@BenjyWiener

Description

@BenjyWiener

Currently recv and recv_streaming are typed as always returning Data, even if decode is set. This means that to satisfy type checkers, we need to use isinstance, cast, etc.

async for chunk in ws.recv_streaming(decode=False):
    assert isinstance(chunk, bytes)
    ...

I propose using typing.overload to narrow the return type when decode is not None:

@overload
async def recv(self, decode: Literal[True]) -> str:
    ...
@overload
async def recv(self, decode: Literal[False]) -> bytes:
    ...
@overload
async def recv(self, decode: None) -> Data:
    ...
async def recv(self, decode: bool | None = None) -> Data:
    """(actual implementation)"""

Alternatively, new recv_str/recv_bytes methods can automatically raise an Exception if the received data is not of the expected type.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions