py/modbuiltins: Fix getattr to work with class raising AttributeError.

Fixes issue #6089.
This commit is contained in:
Damien George 2020-05-29 10:28:38 +10:00
parent da71f55e23
commit 203b10703e
2 changed files with 17 additions and 1 deletions

View File

@ -558,7 +558,11 @@ MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_sorted_obj, 1, mp_builtin_sorted);
static inline mp_obj_t mp_load_attr_default(mp_obj_t base, qstr attr, mp_obj_t defval) {
mp_obj_t dest[2];
// use load_method, raising or not raising exception
((defval == MP_OBJ_NULL) ? mp_load_method : mp_load_method_maybe)(base, attr, dest);
if (defval == MP_OBJ_NULL) {
mp_load_method(base, attr, dest);
} else {
mp_load_method_protected(base, attr, dest, false);
}
if (dest[0] == MP_OBJ_NULL) {
return defval;
} else if (dest[1] == MP_OBJ_NULL) {

View File

@ -16,3 +16,15 @@ print(getattr(a, "meth")(5))
print(getattr(a, "_none_such", 123))
print(getattr(list, "foo", 456))
print(getattr(a, "va" + "r2"))
# test a class that defines __getattr__ and may raise AttributeError
class B:
def __getattr__(self, attr):
if attr == "a":
return attr
else:
raise AttributeError
b = B()
print(getattr(b, "a"))
print(getattr(b, "a", "default"))
print(getattr(b, "b", "default"))