8000 py: Make dir report instance members by dhylands · Pull Request #1756 · micropython/micropython · GitHub
[go: up one dir, main page]

Skip to content

py: Make dir report instance members #1756

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

8000
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion py/modbuiltins.c
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
#include "py/smallint.h"
#include "py/objint.h"
#include "py/objstr.h"
#include "py/objtype.h"
#include "py/runtime0.h"
#include "py/runtime.h"
#include "py/builtin.h"
Expand Down Expand Up @@ -196,6 +197,7 @@ STATIC mp_obj_t mp_builtin_dir(mp_uint_t n_args, const mp_obj_t *args) {
// TODO make this function more general and less of a hack

mp_obj_dict_t *dict = NULL;
mp_map_t *members = NULL;
if (n_args == 0) {
// make a list of names in the local name space
dict = mp_locals_get();
Expand All @@ -214,6 +216,10 @@ STATIC mp_obj_t mp_builtin_dir(mp_uint_t n_args, const mp_obj_t *args) {
dict = type->locals_dict;
}
}
if (mp_obj_is_instance_type(mp_obj_get_type(args[0]))) {
mp_obj_instance_t *inst = args[0];
members = &inst->members;
}
}

mp_obj_t dir = mp_obj_new_list(0, NULL);
Expand All @@ -224,7 +230,13 @@ STATIC mp_obj_t mp_builtin_dir(mp_uint_t n_args, const mp_obj_t *args) {
}
}
}

if (members != NULL) {
for (mp_uint_t i = 0; i < members->alloc; i++) {
if (MP_MAP_SLOT_IS_FILLED(members, i)) {
mp_obj_list_append(dir, members->table[i].key);
}
}
}
return dir;
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_dir_obj, 0, 1, mp_builtin_dir);
Expand Down
7 changes: 7 additions & 0 deletions tests/basics/builtin_dir.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,10 @@
import sys
print('platform' in dir(sys))

class Foo:
def __init__(self):
self.x = 1
foo = Foo()
print('__init__' in dir(foo))
print('x' in dir(foo))

0