[3.13] gh-130851: Don't crash when deduping unusual code constants (GH-130853) (#130880)

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.
(cherry picked from commit 2905690a91)

Co-authored-by: Sam Gross <colesbury@gmail.com>
This commit is contained in:
Miss Islington (bot) 2025-03-05 21:22:57 +01:00 committed by GitHub
parent 39f7b06d35
commit e285232c76
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 32 additions and 6 deletions

View file

@ -596,6 +596,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):