Skip to content

Fall back to utf-8 when charset autodetection needs unread content - #3879

Open
qianeric-backup wants to merge 1 commit into
encode:masterfrom
qianeric-backup:response-encoding-fallback
Open

qianeric-backup wants to merge 1 commit into
encode:masterfrom
qianeric-backup:response-encoding-fallback

Conversation

@qianeric-backup

Copy link
Copy Markdown

Discussed first, as the contributing guide asks: #3878.

Response.encoding caches a charset Python has no codec for when default_encoding is a callable and the content has not been read yet:

>>> response.encoding
'x-user-defined'
>>> b"".join(response.iter_bytes()).decode(response.encoding)
LookupError: unknown encoding: x-user-defined

_is_known_encoding() correctly rejects the header's x-user-defined, and the property then picks a replacement:

        if isinstance(self.default_encoding, str):
            encoding = self.default_encoding
        elif hasattr(self, "_content"):
            encoding = self.default_encoding(self._content)
        ...
        self._encoding = encoding or "utf-8"

A string default_encoding replaces the rejected charset. A callable one with unread content takes neither branch, so encoding is still the rejected value, and or "utf-8" does not catch it because a non-empty string is truthy. The same response via client.get() decodes fine, so whether a response is readable depends on how it was fetched.

The callable form exists for autodetection, which by definition needs the body; before that point there is nothing to detect from, and the line above already falls back to utf-8 when there is no charset at all.

Change

         elif hasattr(self, "_content"):
             encoding = self.default_encoding(self._content)
+        else:
+            # The callable `default_encoding` requires the response content,
+            # which has not been read yet. Fall back to utf-8 rather than
+            # passing an unusable charset through.
+            encoding = None

Tests

Three cases in tests/models/test_responses.py: the streaming call above, the same response read eagerly (unchanged behaviour), and a known charset with unread content (still honoured).

tree suite
master 1417 passed, 1 skipped
master + the tests, _models.py untouched 2 failed, 1418 passed, 1 skipped — both LookupError: unknown encoding: x-user-defined
with this patch 1420 passed, 1 skipped

comm -3 over the failure lists is empty against master and shows exactly the two new tests against the red tree.

18 legal responses compared byte for byte (known and unknown charsets, string and callable default_encoding, eager and streaming reads, absent charset) produce identical output before and after.

ruff format --diff, ruff check, mypy, scripts/sync-version, and coverage --fail-under=100 (100% after the change) are clean.

Noting the guide's point that effort has moved to hip: this is small and contained, but I understand if it is not worth triaging now.

Response.encoding rejects a header charset that is not a Python codec, then
tries to replace it with default_encoding. With a callable default_encoding
and unread content neither the string branch nor the callable branch runs,
so the rejected charset survives `or "utf-8"` (it is truthy) and is cached,
making every later text access raise LookupError.

The callable form is for autodetection, which needs the body; before that
there is nothing to detect from. Fall back to utf-8, as the same line
already does when no charset was given at all.

Discussed in encode#3878.
@qianeric-backup
qianeric-backup marked this pull request as ready for review November 28, 2026 02:58

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

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant