diff options
author | Andrew Leech <andrew.leech@planetinnovation.com.au> | 2020-06-10 10:45:24 +1000 |
---|---|---|
committer | Damien George <damien.p.george@gmail.com> | 2020-06-10 21:58:13 +1000 |
commit | 28370c04509a6255cd3d6b9424443a5b57bb7467 (patch) | |
tree | 98d1f78a1805d14b85a88e54c910e0cf46168598 /py/objtype.c | |
parent | 29e258611ace8e4de51d810d5ff14364a5fbb950 (diff) | |
download | micropython-28370c04509a6255cd3d6b9424443a5b57bb7467.tar.gz micropython-28370c04509a6255cd3d6b9424443a5b57bb7467.zip |
py/objtype: Add __dict__ attribute for class objects.
The behavior mirrors the instance object dict attribute where a copy of the
local attributes are provided (unless the dict is read-only, then that dict
itself is returned, as an optimisation). MicroPython does not support
modifying this dict because the changes will not be reflected in the class.
The feature is only enabled if MICROPY_CPYTHON_COMPAT is set, the same as
the instance version.
Diffstat (limited to 'py/objtype.c')
-rw-r--r-- | py/objtype.c | 15 |
1 files changed, 15 insertions, 0 deletions
diff --git a/py/objtype.c b/py/objtype.c index d08c69e284..cb0fb267c8 100644 --- a/py/objtype.c +++ b/py/objtype.c @@ -1013,6 +1013,21 @@ STATIC void type_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { dest[0] = MP_OBJ_NEW_QSTR(self->name); return; } + #if MICROPY_CPYTHON_COMPAT + if (attr == MP_QSTR___dict__) { + // Returns a read-only dict of the class attributes. + // If the internal locals is not fixed, a copy will be created. + mp_obj_dict_t *dict = self->locals_dict; + if (dict->map.is_fixed) { + dest[0] = MP_OBJ_FROM_PTR(dict); + } else { + dest[0] = mp_obj_dict_copy(MP_OBJ_FROM_PTR(dict)); + dict = MP_OBJ_TO_PTR(dest[0]); + dict->map.is_fixed = 1; + } + return; + } + #endif if (attr == MP_QSTR___bases__) { if (self == &mp_type_object) { dest[0] = mp_const_empty_tuple; |