diff --git a/Lib/test/test_uuid.py b/Lib/test/test_uuid.py index fb278b6c4044c2..9b066e3e32d333 100755 --- a/Lib/test/test_uuid.py +++ b/Lib/test/test_uuid.py @@ -311,6 +311,22 @@ def __str__(self): self.assertEqual(repr(CustomUUID(int=1)), "CustomUUID('custom uuid')") + def test_bad_hex_error_message(self): + # A hex string that does not hold exactly 32 hex digits raises the + # same error message in the C and Python implementations. + for text in ('', + '1234567812345678123456781234567', + '123456781234567812345678123456789', + '{123456781234567812345678123456789}', + '12345678-1234-5678-1234-567812345678-9', + '12345678-1234-5678-1234-56781234567', + '12345678-1234-5678-1234-5678123456'): + with self.subTest(text=text): + with self.assertRaises(ValueError) as cm: + self.uuid.UUID(text) + self.assertEqual(str(cm.exception), + 'badly formed hexadecimal UUID string') + def test_exceptions(self): badvalue = lambda f: self.assertRaises(ValueError, f) badtype = lambda f: self.assertRaises(TypeError, f) diff --git a/Misc/NEWS.d/next/Library/2026-11-08-11-32-44.gh-issue-139122.7CAD4A.rst b/Misc/NEWS.d/next/Library/2026-11-08-11-32-44.gh-issue-139122.7CAD4A.rst new file mode 100644 index 00000000000000..b51079643ad70d --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-08-11-32-44.gh-issue-139122.7CAD4A.rst @@ -0,0 +1,4 @@ +The C implementation of :class:`uuid.UUID` now raises :exc:`ValueError` with +the message "badly formed hexadecimal UUID string" for hex strings that +decode to more or fewer than 16 bytes, matching the pure-Python +implementation. diff --git a/Modules/_uuidmodule.c b/Modules/_uuidmodule.c index 04bce1bd18901b..2483c949b6952d 100644 --- a/Modules/_uuidmodule.c +++ b/Modules/_uuidmodule.c @@ -738,17 +738,19 @@ from_hex(uuidobject *self, PyObject *hex) } if (j > UUID_SIZE || (j == UUID_SIZE && acc_set)) { - PyErr_Format(PyExc_ValueError, - "invalid UUID '%s': decodes to more than 16 bytes", - hex); + PyErr_SetString( + PyExc_ValueError, + "badly formed hexadecimal UUID string" + ); return -1; } } if (j != UUID_SIZE) { - PyErr_Format(PyExc_ValueError, - "invalid UUID '%s': decodes to less than 16 bytes", - hex); + PyErr_SetString( + PyExc_ValueError, + "badly formed hexadecimal UUID string" + ); return -1; }