Skip to content

Commit 7f8be59

Browse files
committed
py: Allow hashing of functions and tuples.
1 parent a925639 commit 7f8be59

3 files changed

Lines changed: 21 additions & 2 deletions

File tree

py/obj.c

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,9 +81,16 @@ machine_int_t mp_obj_hash(mp_obj_t o_in) {
8181
return mp_obj_str_get_hash(o_in);
8282
} else if (MP_OBJ_IS_TYPE(o_in, &none_type)) {
8383
return (machine_int_t)o_in;
84+
} else if (MP_OBJ_IS_TYPE(o_in, &fun_native_type) || MP_OBJ_IS_TYPE(o_in, &fun_bc_type)) {
85+
return (machine_int_t)o_in;
86+
} else if (MP_OBJ_IS_TYPE(o_in, &tuple_type)) {
87+
return mp_obj_tuple_hash(o_in);
88+
89+
// TODO hash class and instances
90+
// TODO delegate to __hash__ method if it exists
91+
8492
} else {
85-
assert(0);
86-
return 0;
93+
nlr_jump(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "unhashable type: '%s'", mp_obj_get_type_str(o_in)));
8794
}
8895
}
8996

py/obj.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,7 @@ mp_obj_t mp_obj_complex_binary_op(int op, mp_float_t lhs_real, mp_float_t lhs_im
330330
extern const mp_obj_type_t tuple_type;
331331
void mp_obj_tuple_get(mp_obj_t self_in, uint *len, mp_obj_t **items);
332332
void mp_obj_tuple_del(mp_obj_t self_in);
333+
machine_int_t mp_obj_tuple_hash(mp_obj_t self_in);
333334

334335
// list
335336
extern const mp_obj_type_t list_type;

py/objtuple.c

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,17 @@ void mp_obj_tuple_del(mp_obj_t self_in) {
218218
m_del_var(mp_obj_tuple_t, mp_obj_t, self->len, self);
219219
}
220220

221+
machine_int_t mp_obj_tuple_hash(mp_obj_t self_in) {
222+
assert(MP_OBJ_IS_TYPE(self_in, &tuple_type));
223+
mp_obj_tuple_t *self = self_in;
224+
// start hash with pointer to empty tuple, to make it fairly unique
225+
machine_int_t hash = (machine_int_t)mp_const_empty_tuple;
226+
for (uint i = 0; i < self->len; i++) {
227+
hash += mp_obj_hash(self->items[i]);
228+
}
229+
return hash;
230+
}
231+
221232
/******************************************************************************/
222233
/* tuple iterator */
223234

0 commit comments

Comments
 (0)