Skip to content

Commit dd4135a

Browse files
committed
py/objset: Use mp_check_self() to check args of set/frozenset methods.
Following how other objects work, set/frozenset methods should use the mp_check_self() macro to check the type of the self argument, because in most cases this check can be a null operation. Saves about 100-180 bytes of code for builds with set and frozenset enabled.
1 parent 0c595fa commit dd4135a

1 file changed

Lines changed: 11 additions & 17 deletions

File tree

py/objset.c

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -57,27 +57,21 @@ STATIC bool is_set_or_frozenset(mp_obj_t o) {
5757
;
5858
}
5959

60-
#if MICROPY_PY_BUILTINS_FROZENSET
61-
STATIC void check_set_or_frozenset(mp_obj_t o) {
62-
if (!is_set_or_frozenset(o)) {
63-
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "'set' object required"));
64-
}
65-
}
66-
#else
67-
#define check_set_or_frozenset(o) check_set(o)
68-
#endif
60+
// This macro is shorthand for mp_check_self to verify the argument is a
61+
// set or frozenset for methods that operate on both of these types.
62+
#define check_set_or_frozenset(o) mp_check_self(is_set_or_frozenset(o))
6963

64+
// This function is used to verify the argument for methods that modify
65+
// the set object, and raises an exception if the arg is a frozenset.
7066
STATIC void check_set(mp_obj_t o) {
71-
if (!MP_OBJ_IS_TYPE(o, &mp_type_set)) {
72-
// Emulate CPython behavior
67+
#if MICROPY_PY_BUILTINS_FROZENSET
68+
if (MP_OBJ_IS_TYPE(o, &mp_type_frozenset)) {
69+
// Mutable method called on frozenset; emulate CPython behavior, eg:
7370
// AttributeError: 'frozenset' object has no attribute 'add'
74-
#if MICROPY_PY_BUILTINS_FROZENSET
75-
if (MP_OBJ_IS_TYPE(o, &mp_type_frozenset)) {
76-
nlr_raise(mp_obj_new_exception_msg(&mp_type_AttributeError, "'frozenset' has no such attribute"));
77-
}
78-
#endif
79-
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "'set' object required"));
71+
nlr_raise(mp_obj_new_exception_msg(&mp_type_AttributeError, "'frozenset' has no such attribute"));
8072
}
73+
#endif
74+
mp_check_self(MP_OBJ_IS_TYPE(o, &mp_type_set));
8175
}
8276

8377
STATIC void set_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {

0 commit comments

Comments
 (0)