Merge dict header to request.headers.raw

Question:

headers.raw is typing.List[typing.Tuple[bytes, bytes]]

I want to merge it into another dict, like the one below:

client.build_request(headers=dict(request.headers.raw) | {"foo": "bar"}),

However I got the error

expected "Union[Headers, Dict[str, str], Dict[bytes, bytes], Sequence[Tuple[str, str]], Sequence[Tuple[bytes, bytes]], None]"

Is there some way to do this? I am using Python 3.10, and I was planning to use the new features on merging dicts

Asked By: Rodrigo

||

Answers:

This is because your dict(request.headers.raw) is of type Dict[bytes, bytes] and {"foo": "bar"} is of type Dict[str, str]. So when you do dict(request.headers.raw) | {"foo": "bar"} it’s of type Dict[bytes|str, bytes|str] which won’t match with the expected headers type hence the error.

So you could do this instead,

client.build_request(headers=dict(request.headers.raw) | {b"foo": b"bar"})
Answered By: Abdul Niyas P M
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.