Skip to content

Accept any Mapping for publish and request headers - #1130

Open
sindrip wants to merge 1 commit into
nats-io:mainfrom
sindrip:headers-mapping
Open

sindrip wants to merge 1 commit into
nats-io:mainfrom
sindrip:headers-mapping

Conversation

@sindrip

@sindrip sindrip commented Nov 22, 2026

Copy link
Copy Markdown

Client.publish, Client.request and JetStream.publish annotate headers as dict[...]. dict is invariant in its value type, so callers holding a precisely typed dict[str, str] fail type checking even though it works at runtime:

headers: dict[str, str] = build_headers()
await nc.publish("subject", payload, headers=headers)
# error: Expected `Headers | dict[str, str | list[str]] | None`, found `dict[str, str]`

The same mismatch shows up inside the repo: JetStream.publish forwards its dict[str, str] headers to Client.request(headers: dict[str, str | list[str]]).

This PR annotates those parameters, and encode_headers, as Mapping[str, str | list[str]]. That's what the code already accepts: it only reads .items() and checks isinstance(value, list), and Headers.__init__ already takes Mapping[str, str | list[str]]. JetStream.publish now also declares the multi-value headers its own tests pass (test_jetstream.py, test_stream.py).

  • No runtime change. Widening a parameter type only accepts more, so existing callers are unaffected.
  • One # type: ignore[arg-type] removed: the one on the encode_headers call in Client.publish, which is no longer needed.
  • Why list[str] and not Sequence[str]: encode_headers only expands list values, so a tuple would be sent as a single value.

Client.publish, Client.request and JetStream.publish annotated their
headers as dict[...]. dict is invariant in its value type, so a caller
holding a precisely typed dict[str, str] failed type checking even though
it works at runtime; this also flagged JetStream.publish's own forwarding
of its headers to Client.request.

Annotate the parameters, and encode_headers, as
Mapping[str, str | list[str]], which is what the code already accepts:
it only reads .items() and checks isinstance(value, list). JetStream.publish
now also declares the multi-value headers its tests already pass.

No runtime change. The type: ignore on the encode_headers call in
publish is no longer needed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants