Skip to content

Cannot iter over messages with an explicit decode parameter #1631

@bfontaine

Description

@bfontaine

Hello (again),

The FAQ says that to avoid closing the connection after one message, one should use async for message in websocket instead of message = websocket.recv(), but then how do you pass an explicit decode parameter?
We obviously can’t pass a parameter to __aiter__, but we could add an explicit method like iter_messages that would take this argument.

Something like:

async def iter_messages(self, decode: bool | None = None) -> AsyncIterator[Data]:
    # code from the current __aiter__ implementation, with decode=decode
    try:
        while True:
            yield await self.recv(decode=decode)
    except ConnectionClosedOK:
        return

def __aiter__(self) -> AsyncIterator[Data]:
    return self.iter_messages(decode=decode)

Then if one wanted to explicitely pass a decode argument, they would use:

for message in websocket.iter_messages(decode=...):
    ...

What do you think? If this sounds good to you I can make a PR.

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