self.assertFalse(haskey({}, []))
self.assertEqual(cm.unraisable.exc_type, TypeError)
self.assertEqual(str(cm.unraisable.exc_value),
- "unhashable type: 'list'")
+ "cannot use 'list' as a dict key "
+ "(unhashable type: 'list')")
with support.catch_unraisable_exception() as cm:
self.assertFalse(haskey([], 1))
import gc
import pickle
import random
+import re
import string
import sys
import unittest
self.assertEqual(d.get(key3_3), 44)
self.assertGreaterEqual(eq_count, 1)
+ def test_unhashable_key(self):
+ d = {'a': 1}
+ key = [1, 2, 3]
+
+ def check_unhashable_key():
+ msg = "cannot use 'list' as a dict key (unhashable type: 'list')"
+ return self.assertRaisesRegex(TypeError, re.escape(msg))
+
+ with check_unhashable_key():
+ key in d
+ with check_unhashable_key():
+ d[key]
+ with check_unhashable_key():
+ d[key] = 2
+ with check_unhashable_key():
+ d.setdefault(key, 2)
+ with check_unhashable_key():
+ d.pop(key)
+ with check_unhashable_key():
+ d.get(key)
+
+ # Only TypeError exception is overriden,
+ # other exceptions are left unchanged.
+ class HashError:
+ def __hash__(self):
+ raise KeyError('error')
+
+ key2 = HashError()
+ with self.assertRaises(KeyError):
+ key2 in d
+ with self.assertRaises(KeyError):
+ d[key2]
+ with self.assertRaises(KeyError):
+ d[key2] = 2
+ with self.assertRaises(KeyError):
+ d.setdefault(key2, 2)
+ with self.assertRaises(KeyError):
+ d.pop(key2)
+ with self.assertRaises(KeyError):
+ d.get(key2)
+
class CAPITest(unittest.TestCase):
""")
popen = script_helper.spawn_python("main.py", cwd=tmp)
stdout, stderr = popen.communicate()
- self.assertEqual(stdout.rstrip(), b"unhashable type: 'substr'")
+ self.assertIn(b"unhashable type: 'substr'", stdout.rstrip())
with open(os.path.join(tmp, "main.py"), "w", encoding='utf-8') as f:
f.write("""
popen = script_helper.spawn_python("main.py", cwd=tmp)
stdout, stderr = popen.communicate()
- self.assertEqual(stdout.rstrip(), b"unhashable type: 'substr'")
+ self.assertIn(b"unhashable type: 'substr'", stdout.rstrip())
# Various issues with sys module
with open(os.path.join(tmp, "main.py"), "w", encoding='utf-8') as f:
-import unittest
-from test import support
-from test.support import warnings_helper
+import collections.abc
+import copy
import gc
-import weakref
+import itertools
import operator
-import copy
import pickle
-from random import randrange, shuffle
+import re
+import unittest
import warnings
-import collections
-import collections.abc
-import itertools
+import weakref
+from random import randrange, shuffle
+from test import support
+from test.support import warnings_helper
+
class PassThru(Exception):
pass
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
--- /dev/null
+Enhance unhashable key/element error messages for :class:`dict` and
+:class:`set`. Patch by Victor Stinner.
"PyDict_GetItemRef() or PyDict_GetItemWithError()");
}
+static void
+dict_unhashtable_type(PyObject *key)
+{
+ PyObject *exc = PyErr_GetRaisedException();
+ assert(exc != NULL);
+ if (!Py_IS_TYPE(exc, (PyTypeObject*)PyExc_TypeError)) {
+ PyErr_SetRaisedException(exc);
+ return;
+ }
+
+ PyErr_Format(PyExc_TypeError,
+ "cannot use '%T' as a dict key (%S)",
+ key, exc);
+ Py_DECREF(exc);
+}
+
Py_ssize_t
_PyDict_LookupIndex(PyDictObject *mp, PyObject *key)
{
Py_hash_t hash = _PyObject_HashFast(key);
if (hash == -1) {
+ dict_unhashtable_type(key);
return -1;
}
Py_hash_t hash = _PyObject_HashFast(key);
if (hash == -1) {
+ dict_unhashtable_type(key);
*result = NULL;
return -1;
}
Py_hash_t hash = _PyObject_HashFast(key);
if (hash == -1) {
+ dict_unhashtable_type(key);
*result = NULL;
return -1;
}
}
hash = _PyObject_HashFast(key);
if (hash == -1) {
+ dict_unhashtable_type(key);
return NULL;
}
assert(PyDict_Check(mp));
Py_hash_t hash = _PyObject_HashFast(key);
if (hash == -1) {
+ dict_unhashtable_type(key);
Py_DECREF(key);
Py_DECREF(value);
return -1;
assert(key);
Py_hash_t hash = _PyObject_HashFast(key);
if (hash == -1) {
+ dict_unhashtable_type(key);
return -1;
}
Py_hash_t hash = _PyObject_HashFast(key);
if (hash == -1) {
+ dict_unhashtable_type(key);
if (result) {
*result = NULL;
}
hash = _PyObject_HashFast(key);
if (hash == -1) {
+ dict_unhashtable_type(key);
return NULL;
}
ix = _Py_dict_lookup_threadsafe(mp, key, hash, &value);
hash = _PyObject_HashFast(key);
if (hash == -1) {
+ dict_unhashtable_type(key);
return NULL;
}
ix = _Py_dict_lookup_threadsafe(self, key, hash, &val);
hash = _PyObject_HashFast(key);
if (hash == -1) {
+ dict_unhashtable_type(key);
if (result) {
*result = NULL;
}
PyDict_Contains(PyObject *op, PyObject *key)
{
Py_hash_t hash = _PyObject_HashFast(key);
-
if (hash == -1) {
+ dict_unhashtable_type(key);
return -1;
}
if (value == NULL) {
Py_hash_t hash = _PyObject_HashFast(name);
if (hash == -1) {
+ dict_unhashtable_type(name);
return -1;
}
return delitem_knownhash_lock_held((PyObject *)dict, name, hash);
return set_add_entry_takeref(so, Py_NewRef(key), hash);
}
+static void
+set_unhashtable_type(PyObject *key)
+{
+ PyObject *exc = PyErr_GetRaisedException();
+ assert(exc != NULL);
+ if (!Py_IS_TYPE(exc, (PyTypeObject*)PyExc_TypeError)) {
+ PyErr_SetRaisedException(exc);
+ return;
+ }
+
+ PyErr_Format(PyExc_TypeError,
+ "cannot use '%T' as a set element (%S)",
+ key, exc);
+ Py_DECREF(exc);
+}
+
int
_PySet_AddTakeRef(PySetObject *so, PyObject *key)
{
Py_hash_t hash = _PyObject_HashFast(key);
if (hash == -1) {
+ set_unhashtable_type(key);
Py_DECREF(key);
return -1;
}
{
Py_hash_t hash = _PyObject_HashFast(key);
if (hash == -1) {
+ set_unhashtable_type(key);
return -1;
}
return set_add_entry(so, key, hash);
{
Py_hash_t hash = _PyObject_HashFast(key);
if (hash == -1) {
+ set_unhashtable_type(key);
return -1;
}
return set_contains_entry(so, key, hash);
{
Py_hash_t hash = _PyObject_HashFast(key);
if (hash == -1) {
+ set_unhashtable_type(key);
return -1;
}
return set_discard_entry(so, key, hash);