Skip to content

Add option to force sending text or binary frames to asyncio broadcast() #1694

Closed

Description

@lampeh

A text argument to broadcast() similar to how send() handles it would allow me to change a line like

websockets.broadcast(connections, data.decode("utf-8")) (only to immediately encode it again) to
websockets.broadcast(connections, data, text=True)

which would also relieve the code at that point from knowing whether data is bytes or str, only that it needs to go into a "Text" frame.

I've been testing this change to asyncio-broadcast so far with no ill effects.

src/websockets/asyncio/connection.py:

def broadcast(
    connections: Iterable[Connection],
    message: DataLike,
    raise_exceptions: bool = False,
    *,
    text: bool | None = None,
) -> None:
"""
...

"""
    if isinstance(message, str):
        if text is None:
            send_method = "send_text"
        message = message.encode()
    elif isinstance(message, BytesLike):
        if text is None:
            send_method = "send_binary"
    else:
        raise TypeError("data must be str or bytes")

    if text is not None:
        send_method = "send_text" if text else "send_binary"

( in a branch here )

What would be the chances of getting type-overrides backported to 13.x? (Mostly j/k, but I have one test environment with Python 3.8/websockets 13 left and the patch applies the same to the 13.x branch but lacks the change to send())

broadcast-text.patch

Activity

  1. aaugustin commented on Jan 21, 2026

    @aaugustin
    Member

    Looks like a valid improvement request. Thank you for the suggestion.

  2. added a commit that references this issue on Jul 10, 2026
    84859e1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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