Skip to content

Commit

Permalink
py: Implement __reversed__ slot.
Browse files Browse the repository at this point in the history
Addresses issue #1073.
  • Loading branch information
dpgeorge committed Jan 21, 2015
1 parent d7f1994 commit 962a5d5
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 0 deletions.
7 changes: 7 additions & 0 deletions py/objreversed.c
Expand Up @@ -39,6 +39,13 @@ typedef struct _mp_obj_reversed_t {
STATIC mp_obj_t reversed_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
mp_arg_check_num(n_args, n_kw, 1, 1, false);

// check if __reversed__ exists, and if so delegate to it
mp_obj_t dest[2];
mp_load_method_maybe(args[0], MP_QSTR___reversed__, dest);
if (dest[0] != MP_OBJ_NULL) {
return mp_call_method_n_kw(0, 0, dest);
}

mp_obj_reversed_t *o = m_new_obj(mp_obj_reversed_t);
o->base.type = type_in;
o->seq = args[0];
Expand Down
1 change: 1 addition & 0 deletions py/qstrdefs.h
Expand Up @@ -74,6 +74,7 @@ Q(__gt__)
Q(__eq__)
Q(__le__)
Q(__ge__)
Q(__reversed__)

Q(micropython)
Q(bytecode)
Expand Down
6 changes: 6 additions & 0 deletions tests/basics/builtin_reversed.py
Expand Up @@ -31,3 +31,9 @@ def __getitem__(self, pos):
return pos + 1
for a in reversed(A()):
print(a)

# user object with __reversed__
class B:
def __reversed__(self):
return [1, 2, 3]
print(reversed(B()))

0 comments on commit 962a5d5

Please sign in to comment.