From 59d125a37ecfcb8674db16850a16c38152aeaa54 Mon Sep 17 00:00:00 2001 From: rahul05ranjan <11793455+rahul05ranjan@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:11:44 +0000 Subject: [PATCH] fix: drop the stray f from the Invalid key TypeError message MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit dumps() with an unencodable key raised TypeError: Invalid key f(1, 2) — a stray f left over in the f-string. Render the offending object with its repr instead, consistent with the nearby f'Illegal JSON5 value: {obj}' and f'{obj!r} is not JSON5 serializable' messages. Fixes #163 Co-authored-by: rahul05ranjan <11793455+rahul05ranjan@users.noreply.github.com> --- json5/lib.py | 2 +- tests/lib_test.py | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/json5/lib.py b/json5/lib.py index 2eaed55..ecf375a 100644 --- a/json5/lib.py +++ b/json5/lib.py @@ -719,7 +719,7 @@ def encode( return s if as_key: - raise TypeError(f'Invalid key f{obj}') + raise TypeError(f'Invalid key: {obj!r}') return self._encode_non_basic_type(obj, seen, level) def _encode_basic_type(self, obj: Any, *, as_key: bool) -> Optional[str]: diff --git a/tests/lib_test.py b/tests/lib_test.py index 6379510..fa85e7e 100644 --- a/tests/lib_test.py +++ b/tests/lib_test.py @@ -827,6 +827,13 @@ def test_invalid_collection(self): # work. self.assertRaises(TypeError, json5.dumps, {1, 2, 3}) + def test_invalid_key_type_message(self): + # Unencodable keys must fail with a clean, correctly-formatted + # message, not one with a stray ``f`` in it. + with self.assertRaises(TypeError) as ctx: + json5.dumps({(1, 2): 'x'}) + self.assertEqual(str(ctx.exception), "Invalid key: (1, 2)") + def test_custom_numbers(self): # See https://github.com/dpranke/pyjson5/issues/57: we # need to ensure that we use the bare int.__repr__ and