Skip to content

Commit

Permalink
py: Make sure getattr() works with non-interned strings (by interning…
Browse files Browse the repository at this point in the history
… them).
  • Loading branch information
Paul Sokolovsky committed Jun 7, 2014
1 parent d31a093 commit b4efac1
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 2 deletions.
9 changes: 7 additions & 2 deletions py/builtin.c
Expand Up @@ -452,12 +452,17 @@ STATIC inline mp_obj_t mp_load_attr_default(mp_obj_t base, qstr attr, mp_obj_t d
}

STATIC mp_obj_t mp_builtin_getattr(uint n_args, const mp_obj_t *args) {
assert(MP_OBJ_IS_QSTR(args[1]));
mp_obj_t attr = args[1];
if (MP_OBJ_IS_TYPE(attr, &mp_type_str)) {
attr = mp_obj_str_intern(attr);
} else if (!MP_OBJ_IS_QSTR(attr)) {
nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "string required"));
}
mp_obj_t defval = MP_OBJ_NULL;
if (n_args > 2) {
defval = args[2];
}
return mp_load_attr_default(args[0], MP_OBJ_QSTR_VALUE(args[1]), defval);
return mp_load_attr_default(args[0], MP_OBJ_QSTR_VALUE(attr), defval);
}

MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_getattr_obj, 2, 3, mp_builtin_getattr);
Expand Down
1 change: 1 addition & 0 deletions py/obj.h
Expand Up @@ -468,6 +468,7 @@ uint mp_obj_str_get_len(mp_obj_t self_in);
qstr mp_obj_str_get_qstr(mp_obj_t self_in); // use this if you will anyway convert the string to a qstr
const char *mp_obj_str_get_str(mp_obj_t self_in); // use this only if you need the string to be null terminated
const char *mp_obj_str_get_data(mp_obj_t self_in, uint *len);
mp_obj_t mp_obj_str_intern(mp_obj_t str);
void mp_str_print_quoted(void (*print)(void *env, const char *fmt, ...), void *env, const byte *str_data, uint str_len);

#if MICROPY_PY_BUILTINS_FLOAT
Expand Down
5 changes: 5 additions & 0 deletions py/objstr.c
Expand Up @@ -1751,6 +1751,11 @@ mp_obj_t mp_obj_new_str(const char* data, uint len, bool make_qstr_if_not_alread
}
}

mp_obj_t mp_obj_str_intern(mp_obj_t str) {
GET_STR_DATA_LEN(str, data, len);
return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
}

mp_obj_t mp_obj_new_bytes(const byte* data, uint len) {
return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
}
Expand Down
1 change: 1 addition & 0 deletions tests/basics/getattr1.py
Expand Up @@ -15,3 +15,4 @@ def meth(self, i):
print(getattr(a, "meth")(5))
print(getattr(a, "_none_such", 123))
print(getattr(list, "foo", 456))
print(getattr(a, "va" + "r2"))

0 comments on commit b4efac1

Please sign in to comment.