Skip to content

Commit 21dfa07

Browse files
committed
py/objdict: Fix __hash__ for dict_view types.
This adds a unary_op implementation for the dict_view type that makes the implementation of `hash()` for these types compatible with CPython. Signed-off-by: David Lechner <david@pybricks.com>
1 parent 0997819 commit 21dfa07

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

py/objdict.c

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -515,6 +515,15 @@ STATIC void dict_view_print(const mp_print_t *print, mp_obj_t self_in, mp_print_
515515
mp_print_str(print, "])");
516516
}
517517

518+
STATIC mp_obj_t dict_view_unary_op(mp_unary_op_t op, mp_obj_t o_in) {
519+
mp_obj_dict_view_t *o = MP_OBJ_TO_PTR(o_in);
520+
// only dict.values() supports __hash__.
521+
if (op == MP_UNARY_OP_HASH && o->kind == MP_DICT_VIEW_VALUES) {
522+
return MP_OBJ_NEW_SMALL_INT((mp_uint_t)o_in);
523+
}
524+
return MP_OBJ_NULL;
525+
}
526+
518527
STATIC mp_obj_t dict_view_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
519528
// only supported for the 'keys' kind until sets and dicts are refactored
520529
mp_obj_dict_view_t *o = MP_OBJ_TO_PTR(lhs_in);
@@ -532,6 +541,7 @@ STATIC MP_DEFINE_CONST_OBJ_TYPE(
532541
MP_QSTR_dict_view,
533542
MP_TYPE_FLAG_ITER_IS_GETITER,
534543
print, dict_view_print,
544+
unary_op, dict_view_unary_op,
535545
binary_op, dict_view_binary_op,
536546
iter, dict_view_getiter
537547
);

tests/basics/dict_views.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,22 @@
1818
except TypeError:
1919
print('TypeError')
2020

21+
# keys dict_view is not hashable
22+
23+
try:
24+
hash({}.keys())
25+
except TypeError:
26+
print('TypeError')
27+
28+
# values dict_view is hashable
29+
30+
print(type(hash({}.values())))
31+
32+
# items dict_view is not hashable
33+
34+
try:
35+
hash({}.items())
36+
except TypeError:
37+
print('TypeError')
38+
2139
# set operations still to come

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy