py/objmodule: Add support for __dict__.
This matches class `__dict__`, and is similarly gated on MICROPY_CPYTHON_COMPAT. Unlike class though, because modules's globals are actually dict instances, the result is a mutable dictionary. This work was funded through GitHub Sponsors. Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
This commit is contained in:
parent
d94141e147
commit
15d0615d5c
|
@ -89,6 +89,10 @@ STATIC void module_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
|
||||||
mp_map_elem_t *elem = mp_map_lookup(&self->globals->map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP);
|
mp_map_elem_t *elem = mp_map_lookup(&self->globals->map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP);
|
||||||
if (elem != NULL) {
|
if (elem != NULL) {
|
||||||
dest[0] = elem->value;
|
dest[0] = elem->value;
|
||||||
|
#if MICROPY_CPYTHON_COMPAT
|
||||||
|
} else if (attr == MP_QSTR___dict__) {
|
||||||
|
dest[0] = MP_OBJ_FROM_PTR(self->globals);
|
||||||
|
#endif
|
||||||
#if MICROPY_MODULE_GETATTR
|
#if MICROPY_MODULE_GETATTR
|
||||||
} else if (attr != MP_QSTR___getattr__) {
|
} else if (attr != MP_QSTR___getattr__) {
|
||||||
elem = mp_map_lookup(&self->globals->map, MP_OBJ_NEW_QSTR(MP_QSTR___getattr__), MP_MAP_LOOKUP);
|
elem = mp_map_lookup(&self->globals->map, MP_OBJ_NEW_QSTR(MP_QSTR___getattr__), MP_MAP_LOOKUP);
|
||||||
|
|
|
@ -0,0 +1,13 @@
|
||||||
|
# test __dict__ attribute of a built-in module
|
||||||
|
# see import/module_dict.py for the equivalent test on user modules
|
||||||
|
|
||||||
|
import sys
|
||||||
|
|
||||||
|
if not hasattr(sys, "__dict__"):
|
||||||
|
print("SKIP")
|
||||||
|
raise SystemExit
|
||||||
|
|
||||||
|
|
||||||
|
# dict of a built-in module (read-only)
|
||||||
|
print(type(sys.__dict__))
|
||||||
|
print(sys.__dict__["__name__"])
|
|
@ -0,0 +1,17 @@
|
||||||
|
# test __dict__ attribute of a user module
|
||||||
|
|
||||||
|
import sys
|
||||||
|
|
||||||
|
if not hasattr(sys, "__dict__"):
|
||||||
|
print("SKIP")
|
||||||
|
raise SystemExit
|
||||||
|
|
||||||
|
|
||||||
|
import import1b
|
||||||
|
|
||||||
|
# dict of a user module (read/write)
|
||||||
|
print(import1b.var)
|
||||||
|
print(import1b.__dict__["var"])
|
||||||
|
import1b.__dict__["var"] = "hello"
|
||||||
|
print(import1b.var)
|
||||||
|
print(import1b.__dict__["var"])
|
Loading…
Reference in New Issue