Skip to content

Commit 25f417c

Browse files
committed
Worked on list.pop:
* Fixes issue adafruit#51 * Adds a specific error message for when you try to pop an empty list. * Releases some memory if the list has shurnk a lot.
1 parent 9bc56d9 commit 25f417c

2 files changed

Lines changed: 24 additions & 5 deletions

File tree

py/objlist.c

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -76,13 +76,21 @@ mp_obj_t mp_obj_list_append(mp_obj_t self_in, mp_obj_t arg) {
7676
return mp_const_none; // return None, as per CPython
7777
}
7878

79-
static mp_obj_t list_pop(mp_obj_t self_in, mp_obj_t arg) {
80-
assert(MP_OBJ_IS_TYPE(self_in, &list_type));
81-
mp_obj_list_t *self = self_in;
82-
uint index = mp_get_index(self->base.type, self->len, arg);
79+
static mp_obj_t list_pop(int n_args, const mp_obj_t *args) {
80+
assert(1 <= n_args && n_args <= 2);
81+
assert(MP_OBJ_IS_TYPE(args[0], &list_type));
82+
mp_obj_list_t *self = args[0];
83+
if (self->len == 0) {
84+
nlr_jump(mp_obj_new_exception_msg(rt_q_IndexError, "pop from empty list"));
85+
}
86+
uint index = mp_get_index(self->base.type, self->len, n_args == 1 ? mp_obj_new_int(-1) : args[1]);
8387
mp_obj_t ret = self->items[index];
8488
self->len -= 1;
8589
memcpy(self->items + index, self->items + index + 1, (self->len - index) * sizeof(mp_obj_t));
90+
if (self->alloc > 2 * self->len) {
91+
self->items = m_renew(mp_obj_t, self->items, self->alloc, self->alloc/2);
92+
self->alloc /= 2;
93+
}
8694
return ret;
8795
}
8896

@@ -118,7 +126,7 @@ static mp_obj_t list_sort(mp_obj_t self_in, mp_obj_t key_fn) {
118126
}
119127

120128
static MP_DEFINE_CONST_FUN_OBJ_2(list_append_obj, mp_obj_list_append);
121-
static MP_DEFINE_CONST_FUN_OBJ_2(list_pop_obj, list_pop);
129+
static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(list_pop_obj, 1, 2, list_pop);
122130
static MP_DEFINE_CONST_FUN_OBJ_2(list_sort_obj, list_sort);
123131

124132
const mp_obj_type_t list_type = {

tests/basics/tests/list3.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# list poppin'
2+
a = [1, 2, 3]
3+
print(a.pop())
4+
print(a.pop())
5+
print(a.pop())
6+
try:
7+
print(a.pop())
8+
except IndexError:
9+
print("IndexError raised")
10+
else:
11+
raise AssertionError("No IndexError raised")

0 commit comments

Comments
 (0)