gh-132825: Enhance unhashable error messages for dict and set (#132828)

This commit is contained in:
Victor Stinner 2025-04-23 17:10:09 +02:00 committed by GitHub
parent b2e666f30a
commit 426449d983
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 136 additions and 14 deletions

View file

@ -1,16 +1,17 @@
import collections.abc
import copy
import gc
import itertools
import operator
import pickle
import re
import unittest
import warnings
import weakref
from random import randrange, shuffle
from test import support
from test.support import warnings_helper
import gc
import weakref
import operator
import copy
import pickle
from random import randrange, shuffle
import warnings
import collections
import collections.abc
import itertools
class PassThru(Exception):
pass
@ -645,6 +646,35 @@ class TestSet(TestJointOps, unittest.TestCase):
self.assertRaises(KeyError, myset.remove, set(range(1)))
self.assertRaises(KeyError, myset.remove, set(range(3)))
def test_unhashable_element(self):
myset = {'a'}
elem = [1, 2, 3]
def check_unhashable_element():
msg = "cannot use 'list' as a set element (unhashable type: 'list')"
return self.assertRaisesRegex(TypeError, re.escape(msg))
with check_unhashable_element():
elem in myset
with check_unhashable_element():
myset.add(elem)
with check_unhashable_element():
myset.discard(elem)
# Only TypeError exception is overriden,
# other exceptions are left unchanged.
class HashError:
def __hash__(self):
raise KeyError('error')
elem2 = HashError()
with self.assertRaises(KeyError):
elem2 in myset
with self.assertRaises(KeyError):
myset.add(elem2)
with self.assertRaises(KeyError):
myset.discard(elem2)
class SetSubclass(set):
pass