py: Add support for start/stop/step attributes of builtin range object.

This commit is contained in:
Peter D. Gray 2015-03-06 14:48:14 -05:00 committed by Damien George
parent 5be4a84a58
commit b2a237d337
4 changed files with 33 additions and 0 deletions

View File

@ -382,6 +382,12 @@ typedef double mp_float_t;
#define MICROPY_PY_BUILTINS_PROPERTY (1)
#endif
// Whether to implement the start/stop/step attributes (readback) on
// the "range" builtin type. Rarely used, and costs ~60 bytes (x86).
#ifndef MICROPY_PY_BUILTINS_RANGE_ATTRS
#define MICROPY_PY_BUILTINS_RANGE_ATTRS (1)
#endif
// Whether to support complete set of special methods
// for user classes, otherwise only the most used
#ifndef MICROPY_PY_ALL_SPECIAL_METHODS

View File

@ -166,6 +166,20 @@ STATIC mp_obj_t range_getiter(mp_obj_t o_in) {
return mp_obj_new_range_iterator(o->start, o->stop, o->step);
}
#if MICROPY_PY_BUILTINS_RANGE_ATTRS
STATIC void range_load_attr(mp_obj_t o_in, qstr attr, mp_obj_t *dest) {
mp_obj_range_t *o = o_in;
if (attr == MP_QSTR_start) {
dest[0] = mp_obj_new_int(o->start);
} else if (attr == MP_QSTR_stop) {
dest[0] = mp_obj_new_int(o->stop);
} else if (attr == MP_QSTR_step) {
dest[0] = mp_obj_new_int(o->step);
}
}
#endif
const mp_obj_type_t mp_type_range = {
{ &mp_type_type },
.name = MP_QSTR_range,
@ -174,4 +188,7 @@ const mp_obj_type_t mp_type_range = {
.unary_op = range_unary_op,
.subscr = range_subscr,
.getiter = range_getiter,
#if MICROPY_PY_BUILTINS_RANGE_ATTRS
.load_attr = range_load_attr,
#endif
};

View File

@ -245,6 +245,11 @@ Q(single)
Q(sep)
Q(end)
#if MICROPY_PY_BUILTINS_RANGE_ATTRS
Q(step)
Q(stop)
#endif
Q(clear)
Q(copy)
Q(fromkeys)

View File

@ -24,3 +24,8 @@ print(range(4)[1:2])
print(range(4)[1:3])
print(range(4)[1::2])
print(range(4)[1:-2:2])
# attrs
print(range(1, 2, 3).start)
print(range(1, 2, 3).stop)
print(range(1, 2, 3).step)