Skip to content

Headers: looking up a bytes key with in/get/__getitem__ raises AttributeError #3898

Backlog

Description

@KaelLee335

Description

HeaderTypes publicly accepts Mapping[bytes, bytes] and Sequence[Tuple[bytes, bytes]], and Headers normalizes bytes keys on construction — Headers({b"X-Foo": b"bar"}) builds fine and h.keys() returns ['x-foo']. But looking a key back up with the same bytes type crashes: __getitem__, __delitem__, __contains__ and get() all call key.lower().encode(self.encoding), which raises AttributeError for bytes (bytes.lower() returns bytes, which has no .encode()).

So the same type is accepted for construction but rejected for lookup — an internal inconsistency in one API.

Steps to reproduce

from httpx import Headers

h = Headers({b"X-Foo": b"bar"})
print("keys:", list(h.keys()))          # ['x-foo']
print("'x-foo' in h:", "x-foo" in h)    # True
print("b'x-foo' in h:", b"x-foo" in h)  # AttributeError
print("h.get(b'x-foo'):", h.get(b"x-foo"))  # AttributeError

Actual output:

keys: ['x-foo']
'x-foo' in h: True
b'x-foo' in h raised: AttributeError("'bytes' object has no attribute 'encode'")
h.get(b'x-foo') raised: AttributeError("'bytes' object has no attribute 'encode'")

Expected behavior

b"x-foo" in h, h[b"x-foo"] and h.get(b"x-foo") should work just like their str counterparts, since bytes keys are explicitly part of the accepted input types and are normalized on construction.

Suggested fix

Use the existing _normalize_header_key(key, self.encoding) helper in __getitem__ / __delitem__ / __contains__ instead of key.lower().encode(self.encoding). That helper already handles both str and bytes.

Environment

  • httpx 0.29.0 (main @ e347fb5)
  • Python 3.13

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions