gh-130851: Don't crash when deduping unusual code constants (#130853)

The bytecode compiler only generates a few different types of constants,
like str, int, tuple, slices, etc. Users can construct code objects with
various unusual constants, including ones that are not hashable or not
even constant.

The free threaded build previously crashed with a fatal error when
confronted with these constants. Instead, treat distinct objects of
otherwise unhandled types as not equal for the purposes of deduplication.
This commit is contained in:
Sam Gross 2025-03-05 09:04:49 -05:00 committed by GitHub
parent 78d50e91ff
commit 2905690a91
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 32 additions and 6 deletions

View file

@ -665,6 +665,23 @@ class CodeConstsTest(unittest.TestCase):
self.assertTrue(globals["func1"]() is globals["func2"]())
@cpython_only
def test_unusual_constants(self):
# gh-130851: Code objects constructed with constants that are not
# types generated by the bytecode compiler should not crash the
# interpreter.
class Unhashable:
def __hash__(self):
raise TypeError("unhashable type")
class MyInt(int):
pass
code = compile("a = 1", "<string>", "exec")
code = code.replace(co_consts=(1, Unhashable(), MyInt(1), MyInt(1)))
self.assertIsInstance(code.co_consts[1], Unhashable)
self.assertEqual(code.co_consts[2], code.co_consts[3])
class CodeWeakRefTest(unittest.TestCase):