Skip to content

Commit 8b3b2d0

Browse files
committed
objset: frozensets are hashable.
1 parent 936e25b commit 8b3b2d0

3 files changed

Lines changed: 25 additions & 0 deletions

File tree

py/objset.c

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,22 @@ STATIC mp_obj_t set_unary_op(mp_uint_t op, mp_obj_t self_in) {
473473
switch (op) {
474474
case MP_UNARY_OP_BOOL: return MP_BOOL(self->set.used != 0);
475475
case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(self->set.used);
476+
#if MICROPY_PY_BUILTINS_FROZENSET
477+
case MP_UNARY_OP_HASH:
478+
if (MP_OBJ_IS_TYPE(self_in, &mp_type_frozenset)) {
479+
// start hash with unique value
480+
mp_int_t hash = (mp_int_t)&mp_type_frozenset;
481+
mp_uint_t max = self->set.alloc;
482+
mp_set_t *set = &self->set;
483+
484+
for (mp_uint_t i = 0; i < max; i++) {
485+
if (MP_SET_SLOT_IS_FILLED(set, i)) {
486+
hash += MP_OBJ_SMALL_INT_VALUE(mp_unary_op(MP_UNARY_OP_HASH, set->table[i]));
487+
}
488+
}
489+
return MP_OBJ_NEW_SMALL_INT(hash);
490+
}
491+
#endif
476492
default: return MP_OBJ_NULL; // op not supported
477493
}
478494
}

tests/basics/frozenset1.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,6 @@
1515

1616
s = frozenset({3, 4, 3, 1})
1717
print(sorted(s))
18+
19+
# frozensets are hashable unlike sets
20+
print({frozenset("1"): 2})

tests/basics/set1.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,9 @@
55

66
s = {3, 4, 3, 1}
77
print(sorted(s))
8+
9+
# Sets are not hashable
10+
try:
11+
{s: 1}
12+
except TypeError:
13+
print("TypeError")

0 commit comments

Comments
 (0)