Skip to content

Commit b2a237d

Browse files
doc-hexdpgeorge
authored andcommitted
py: Add support for start/stop/step attributes of builtin range object.
1 parent 5be4a84 commit b2a237d

4 files changed

Lines changed: 33 additions & 0 deletions

File tree

py/mpconfig.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,12 @@ typedef double mp_float_t;
382382
#define MICROPY_PY_BUILTINS_PROPERTY (1)
383383
#endif
384384

385+
// Whether to implement the start/stop/step attributes (readback) on
386+
// the "range" builtin type. Rarely used, and costs ~60 bytes (x86).
387+
#ifndef MICROPY_PY_BUILTINS_RANGE_ATTRS
388+
#define MICROPY_PY_BUILTINS_RANGE_ATTRS (1)
389+
#endif
390+
385391
// Whether to support complete set of special methods
386392
// for user classes, otherwise only the most used
387393
#ifndef MICROPY_PY_ALL_SPECIAL_METHODS

py/objrange.c

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,20 @@ STATIC mp_obj_t range_getiter(mp_obj_t o_in) {
166166
return mp_obj_new_range_iterator(o->start, o->stop, o->step);
167167
}
168168

169+
170+
#if MICROPY_PY_BUILTINS_RANGE_ATTRS
171+
STATIC void range_load_attr(mp_obj_t o_in, qstr attr, mp_obj_t *dest) {
172+
mp_obj_range_t *o = o_in;
173+
if (attr == MP_QSTR_start) {
174+
dest[0] = mp_obj_new_int(o->start);
175+
} else if (attr == MP_QSTR_stop) {
176+
dest[0] = mp_obj_new_int(o->stop);
177+
} else if (attr == MP_QSTR_step) {
178+
dest[0] = mp_obj_new_int(o->step);
179+
}
180+
}
181+
#endif
182+
169183
const mp_obj_type_t mp_type_range = {
170184
{ &mp_type_type },
171185
.name = MP_QSTR_range,
@@ -174,4 +188,7 @@ const mp_obj_type_t mp_type_range = {
174188
.unary_op = range_unary_op,
175189
.subscr = range_subscr,
176190
.getiter = range_getiter,
191+
#if MICROPY_PY_BUILTINS_RANGE_ATTRS
192+
.load_attr = range_load_attr,
193+
#endif
177194
};

py/qstrdefs.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,11 @@ Q(single)
245245
Q(sep)
246246
Q(end)
247247

248+
#if MICROPY_PY_BUILTINS_RANGE_ATTRS
249+
Q(step)
250+
Q(stop)
251+
#endif
252+
248253
Q(clear)
249254
Q(copy)
250255
Q(fromkeys)

tests/basics/builtin_range.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,8 @@
2424
print(range(4)[1:3])
2525
print(range(4)[1::2])
2626
print(range(4)[1:-2:2])
27+
28+
# attrs
29+
print(range(1, 2, 3).start)
30+
print(range(1, 2, 3).stop)
31+
print(range(1, 2, 3).step)

0 commit comments

Comments
 (0)