Skip to content

Commit 7281d95

Browse files
dhylandspfalcon
authored andcommitted
py: Make dir report instance members
1 parent b50030b commit 7281d95

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

py/modbuiltins.c

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
#include "py/smallint.h"
3232
#include "py/objint.h"
3333
#include "py/objstr.h"
34+
#include "py/objtype.h"
3435
#include "py/runtime0.h"
3536
#include "py/runtime.h"
3637
#include "py/builtin.h"
@@ -196,6 +197,7 @@ STATIC mp_obj_t mp_builtin_dir(mp_uint_t n_args, const mp_obj_t *args) {
196197
// TODO make this function more general and less of a hack
197198

198199
mp_obj_dict_t *dict = NULL;
200+
mp_map_t *members = NULL;
199201
if (n_args == 0) {
200202
// make a list of names in the local name space
201203
dict = mp_locals_get();
@@ -214,6 +216,10 @@ STATIC mp_obj_t mp_builtin_dir(mp_uint_t n_args, const mp_obj_t *args) {
214216
dict = type->locals_dict;
215217
}
216218
}
219+
if (mp_obj_is_instance_type(mp_obj_get_type(args[0]))) {
220+
mp_obj_instance_t *inst = args[0];
221+
members = &inst->members;
222+
}
217223
}
218224

219225
mp_obj_t dir = mp_obj_new_list(0, NULL);
@@ -224,7 +230,13 @@ STATIC mp_obj_t mp_builtin_dir(mp_uint_t n_args, const mp_obj_t *args) {
224230
}
225231
}
226232
}
227-
233+
if (members != NULL) {
234+
for (mp_uint_t i = 0; i < members->alloc; i++) {
235+
if (MP_MAP_SLOT_IS_FILLED(members, i)) {
236+
mp_obj_list_append(dir, members->table[i].key);
237+
}
238+
}
239+
}
228240
return dir;
229241
}
230242
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_dir_obj, 0, 1, mp_builtin_dir);

tests/basics/builtin_dir.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,10 @@
77
import sys
88
print('platform' in dir(sys))
99

10+
class Foo:
11+
def __init__(self):
12+
self.x = 1
13+
foo = Foo()
14+
print('__init__' in dir(foo))
15+
print('x' in dir(foo))
16+

0 commit comments

Comments
 (0)