Skip to content

Commit 0e3f29c

Browse files
committed
py: Check that second argument to hasattr is actually a string.
Fixes issue adafruit#1623.
1 parent a8aa199 commit 0e3f29c

2 files changed

Lines changed: 12 additions & 2 deletions

File tree

py/modbuiltins.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -529,14 +529,14 @@ STATIC mp_obj_t mp_builtin_setattr(mp_obj_t base, mp_obj_t attr, mp_obj_t value)
529529
MP_DEFINE_CONST_FUN_OBJ_3(mp_builtin_setattr_obj, mp_builtin_setattr);
530530

531531
STATIC mp_obj_t mp_builtin_hasattr(mp_obj_t object_in, mp_obj_t attr_in) {
532-
assert(MP_OBJ_IS_QSTR(attr_in));
532+
qstr attr = mp_obj_str_get_qstr(attr_in);
533533

534534
mp_obj_t dest[2];
535535
// TODO: https://docs.python.org/3/library/functions.html?highlight=hasattr#hasattr
536536
// explicitly says "This is implemented by calling getattr(object, name) and seeing
537537
// whether it raises an AttributeError or not.", so we should explicitly wrap this
538538
// in nlr_push and handle exception.
539-
mp_load_method_maybe(object_in, MP_OBJ_QSTR_VALUE(attr_in), dest);
539+
mp_load_method_maybe(object_in, attr, dest);
540540

541541
return mp_obj_new_bool(dest[0] != MP_OBJ_NULL);
542542
}

tests/basics/hasattr1.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,13 @@ def __getattr__(self, attr):
2727
print(hasattr(c, "exists"))
2828
# TODO
2929
#print(hasattr(c, "doesnt_exist"))
30+
31+
try:
32+
hasattr(1, b'123')
33+
except TypeError:
34+
print('TypeError')
35+
36+
try:
37+
hasattr(1, 123)
38+
except TypeError:
39+
print('TypeError')

0 commit comments

Comments
 (0)