Skip to content

Commit 624eff6

Browse files
committed
Implement tuple.index().
1 parent 0cd1dc0 commit 624eff6

3 files changed

Lines changed: 41 additions & 3 deletions

File tree

py/objtuple.c

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,18 @@ static mp_obj_t tuple_getiter(mp_obj_t o_in) {
153153
return mp_obj_new_tuple_iterator(o_in, 0);
154154
}
155155

156+
static mp_obj_t tuple_index(uint n_args, const mp_obj_t *args) {
157+
assert(MP_OBJ_IS_TYPE(args[0], &tuple_type));
158+
mp_obj_tuple_t *self = args[0];
159+
return mp_seq_index_obj(self->items, self->len, n_args, args);
160+
}
161+
static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(tuple_index_obj, 2, 4, tuple_index);
162+
163+
static const mp_method_t tuple_type_methods[] = {
164+
{ "index", &tuple_index_obj },
165+
{ NULL, NULL }, // end-of-list sentinel
166+
};
167+
156168
const mp_obj_type_t tuple_type = {
157169
{ &mp_const_type },
158170
"tuple",
@@ -161,6 +173,7 @@ const mp_obj_type_t tuple_type = {
161173
.unary_op = tuple_unary_op,
162174
.binary_op = tuple_binary_op,
163175
.getiter = tuple_getiter,
176+
.methods = tuple_type_methods,
164177
};
165178

166179
// the zero-length tuple

py/sequence.c

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -156,9 +156,10 @@ mp_obj_t mp_seq_index_obj(const mp_obj_t *items, uint len, uint n_args, const mp
156156
}
157157

158158
for (uint i = start; i < stop; i++) {
159-
if (mp_obj_equal(items[i], value)) {
160-
return mp_obj_new_int_from_uint(i);
161-
}
159+
if (mp_obj_equal(items[i], value)) {
160+
// Common sense says this cannot overflow small int
161+
return MP_OBJ_NEW_SMALL_INT(i);
162+
}
162163
}
163164

164165
nlr_jump(mp_obj_new_exception_msg(MP_QSTR_ValueError, "object not in sequence"));

tests/basics/tuple_index.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
a = (1, 2, 3)
2+
print(a.index(1))
3+
print(a.index(2))
4+
print(a.index(3))
5+
print(a.index(3, 2))
6+
try:
7+
print(a.index(3, 2, 2))
8+
except ValueError:
9+
print("Raised ValueError")
10+
else:
11+
print("Did not raise ValueError")
12+
13+
a = a + a
14+
b = (0, 0, a)
15+
print(a.index(2))
16+
print(b.index(a))
17+
print(a.index(2, 2))
18+
19+
try:
20+
a.index(2, 2, 2)
21+
except ValueError:
22+
print("Raised ValueError")
23+
else:
24+
print("Did not raise ValueError")

0 commit comments

Comments
 (0)