8000 py: Implement __dict__ for instances by stinos · Pull Request #1757 · micropython/micropython · GitHub
[go: up one dir, main page]

Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion py/objtype.c
Original file line number Diff line number Diff line change
Expand Up @@ -472,7 +472,22 @@ STATIC void mp_obj_instance_load_attr(mp_obj_t self_in, qstr attr, mp_obj_t *des
dest[0] = elem->value;
return;
}

#if MICROPY_CPYTHON_COMPAT
if (attr == MP_QSTR___dict__) {
// Create a new dict with a copy of the instance's map items.
// This creates, unlike CPython, a 'read-only' __dict__: modifying
// it will not result in modifications to the actual instance members.
mp_map_t *map = &(self->members);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's up with those parentheses?

mp_obj_t attr_dict = mp_obj_new_dict(0);
for (mp_uint_t i = 0; i < map->alloc; ++i) {
if (MP_MAP_SLOT_IS_FILLED(map, i)) {
mp_obj_dict_store(attr_dict, map->table[i].key, map->table[i].value);
}
}
dest[0] = attr_dict;
return;
}
#endif
struct class_lookup_data lookup = {
.obj = self,
.attr = attr,
Expand Down
1 change: 1 addition & 0 deletions py/qstrdefs.h
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ Q(__locals__)
Q(__main__)
Q(__module__)
Q(__name__)
Q(__dict__)
Q(__hash__)
Q(__next__)
Q(__qualname__)
Expand Down
11 changes: 11 additions & 0 deletions tests/basics/builtin_dict.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
class A:
def __init__(self):
self.a=1
self.b=2

try:
d=A().__dict__
print(d['a'])
print(d['b'])
except AttributeError:
print("SKIP")
< 3193 div hidden> Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
0