Skip to content

Commit 4c03b3a

Browse files
committed
py: Implement builtin reversed() function.
reversed function now implemented, and works for tuple, list, str, bytes and user objects with __len__ and __getitem__. Renamed mp_builtin_len to mp_obj_len to make it publically available (eg for reversed).
1 parent 69c5fe1 commit 4c03b3a

9 files changed

Lines changed: 125 additions & 12 deletions

File tree

py/builtin.c

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -284,17 +284,6 @@ STATIC mp_obj_t mp_builtin_iter(mp_obj_t o_in) {
284284

285285
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_iter_obj, mp_builtin_iter);
286286

287-
STATIC mp_obj_t mp_builtin_len(mp_obj_t o_in) {
288-
mp_obj_t len = mp_obj_len_maybe(o_in);
289-
if (len == MP_OBJ_NULL) {
290-
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "object of type '%s' has no len()", mp_obj_get_type_str(o_in)));
291-
} else {
292-
return len;
293-
}
294-
}
295-
296-
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_len_obj, mp_builtin_len);
297-
298287
STATIC mp_obj_t mp_builtin_max(uint n_args, const mp_obj_t *args) {
299288
if (n_args == 1) {
300289
// given an iterable
@@ -569,6 +558,7 @@ STATIC mp_obj_t mp_builtin_hasattr(mp_obj_t object_in, mp_obj_t attr_in) {
569558

570559
MP_DEFINE_CONST_FUN_OBJ_2(mp_builtin_hasattr_obj, mp_builtin_hasattr);
571560

572-
// These two are defined in terms of MicroPython API functions right away
561+
// These are defined in terms of MicroPython API functions right away
562+
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_len_obj, mp_obj_len);
573563
MP_DEFINE_CONST_FUN_OBJ_0(mp_builtin_globals_obj, mp_globals_get);
574564
MP_DEFINE_CONST_FUN_OBJ_0(mp_builtin_locals_obj, mp_locals_get);

py/builtin.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626

2727
mp_obj_t mp_builtin___import__(uint n_args, mp_obj_t *args);
2828
mp_obj_t mp_builtin_open(uint n_args, const mp_obj_t *args);
29+
mp_obj_t mp_builtin_len(mp_obj_t o);
2930

3031
MP_DECLARE_CONST_FUN_OBJ(mp_builtin___build_class___obj);
3132
MP_DECLARE_CONST_FUN_OBJ(mp_builtin___import___obj);

py/builtintables.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ STATIC const mp_map_elem_t mp_builtin_object_table[] = {
6666
{ MP_OBJ_NEW_QSTR(MP_QSTR_property), (mp_obj_t)&mp_type_property },
6767
#endif
6868
{ MP_OBJ_NEW_QSTR(MP_QSTR_range), (mp_obj_t)&mp_type_range },
69+
{ MP_OBJ_NEW_QSTR(MP_QSTR_reversed), (mp_obj_t)&mp_type_reversed },
6970
#if MICROPY_PY_BUILTINS_SET
7071
{ MP_OBJ_NEW_QSTR(MP_QSTR_set), (mp_obj_t)&mp_type_set },
7172
#endif

py/obj.c

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,16 @@ uint mp_get_index(const mp_obj_type_t *type, mp_uint_t len, mp_obj_t index, bool
360360
return i;
361361
}
362362

363+
// will raise a TypeError if object has no length
364+
mp_obj_t mp_obj_len(mp_obj_t o_in) {
365+
mp_obj_t len = mp_obj_len_maybe(o_in);
366+
if (len == MP_OBJ_NULL) {
367+
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "object of type '%s' has no len()", mp_obj_get_type_str(o_in)));
368+
} else {
369+
return len;
370+
}
371+
}
372+
363373
// may return MP_OBJ_NULL
364374
mp_obj_t mp_obj_len_maybe(mp_obj_t o_in) {
365375
if (

py/obj.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,7 @@ extern const mp_obj_type_t mp_type_classmethod;
312312
extern const mp_obj_type_t mp_type_property;
313313
extern const mp_obj_type_t mp_type_stringio;
314314
extern const mp_obj_type_t mp_type_bytesio;
315+
extern const mp_obj_type_t mp_type_reversed;
315316

316317
// Exceptions
317318
extern const mp_obj_type_t mp_type_BaseException;
@@ -424,6 +425,7 @@ void mp_obj_get_complex(mp_obj_t self_in, mp_float_t *real, mp_float_t *imag);
424425
void mp_obj_get_array(mp_obj_t o, uint *len, mp_obj_t **items);
425426
void mp_obj_get_array_fixed_n(mp_obj_t o, uint len, mp_obj_t **items);
426427
uint mp_get_index(const mp_obj_type_t *type, mp_uint_t len, mp_obj_t index, bool is_slice);
428+
mp_obj_t mp_obj_len(mp_obj_t o_in);
427429
mp_obj_t mp_obj_len_maybe(mp_obj_t o_in); /* may return MP_OBJ_NULL */
428430
mp_obj_t mp_obj_subscr(mp_obj_t base, mp_obj_t index, mp_obj_t val);
429431

py/objreversed.c

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/*
2+
* This file is part of the Micro Python project, http://micropython.org/
3+
*
4+
* The MIT License (MIT)
5+
*
6+
* Copyright (c) 2014 Damien P. George
7+
*
8+
* Permission is hereby granted, free of charge, to any person obtaining a copy
9+
* of this software and associated documentation files (the "Software"), to deal
10+
* in the Software without restriction, including without limitation the rights
11+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12+
* copies of the Software, and to permit persons to whom the Software is
13+
* furnished to do so, subject to the following conditions:
14+
*
15+
* The above copyright notice and this permission notice shall be included in
16+
* all copies or substantial portions of the Software.
17+
*
18+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24+
* THE SOFTWARE.
25+
*/
26+
27+
#include <stdlib.h>
28+
#include <assert.h>
29+
30+
#include "mpconfig.h"
31+
#include "nlr.h"
32+
#include "misc.h"
33+
#include "qstr.h"
34+
#include "obj.h"
35+
#include "runtime.h"
36+
37+
typedef struct _mp_obj_reversed_t {
38+
mp_obj_base_t base;
39+
mp_obj_t seq; // sequence object that we are reversing
40+
mp_uint_t cur_index; // current index, plus 1; 0=no more, 1=last one (index 0)
41+
} mp_obj_reversed_t;
42+
43+
STATIC mp_obj_t reversed_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
44+
mp_arg_check_num(n_args, n_kw, 1, 1, false);
45+
46+
mp_obj_reversed_t *o = m_new_obj(mp_obj_reversed_t);
47+
o->base.type = &mp_type_reversed;
48+
o->seq = args[0];
49+
o->cur_index = mp_obj_get_int(mp_obj_len(args[0])); // start at the end of the sequence
50+
51+
return o;
52+
}
53+
54+
STATIC mp_obj_t reversed_iternext(mp_obj_t self_in) {
55+
assert(MP_OBJ_IS_TYPE(self_in, &mp_type_reversed));
56+
mp_obj_reversed_t *self = self_in;
57+
58+
// "raise" stop iteration if we are at the end (the start) of the sequence
59+
if (self->cur_index == 0) {
60+
return MP_OBJ_STOP_ITERATION;
61+
}
62+
63+
// pre-decrement and index sequence
64+
self->cur_index -= 1;
65+
return mp_obj_subscr(self->seq, MP_OBJ_NEW_SMALL_INT(self->cur_index), MP_OBJ_SENTINEL);
66+
}
67+
68+
const mp_obj_type_t mp_type_reversed = {
69+
{ &mp_type_type },
70+
.name = MP_QSTR_reversed,
71+
.make_new = reversed_make_new,
72+
.getiter = mp_identity,
73+
.iternext = reversed_iternext,
74+
};

py/py.mk

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ PY_O_BASENAME = \
7272
objnone.o \
7373
objnamedtuple.o \
7474
objrange.o \
75+
objreversed.o \
7576
objset.o \
7677
objslice.o \
7778
objstr.o \

py/qstrdefs.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,7 @@ Q(print)
175175
Q(range)
176176
Q(read)
177177
Q(repr)
178+
Q(reversed)
178179
Q(set)
179180
Q(sorted)
180181
Q(staticmethod)

tests/basics/builtin_reversed.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# test the builtin reverse() function
2+
3+
# list
4+
print(list(reversed([])))
5+
print(list(reversed([1])))
6+
print(list(reversed([1, 2, 3])))
7+
8+
# tuple
9+
print(list(reversed(())))
10+
print(list(reversed((1, 2, 3))))
11+
12+
# string
13+
for c in reversed('ab'):
14+
print(c)
15+
16+
# bytes
17+
for b in reversed(b'1234'):
18+
print(b)
19+
20+
# range
21+
#for i in reversed(range(3)):
22+
# print(i)
23+
24+
# user object
25+
class A:
26+
def __init__(self):
27+
pass
28+
def __len__(self):
29+
return 3
30+
def __getitem__(self, pos):
31+
return pos + 1
32+
for a in reversed(A()):
33+
print(a)

0 commit comments

Comments
 (0)