Skip to content

Commit 7b27fbf

Browse files
committed
Add list.pop
Also include IndexError in the __builtin__ module.
1 parent 328f81a commit 7b27fbf

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

tests/snippets/list.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,11 @@
2020
pass
2121
else:
2222
assert False, "ValueError was not raised"
23+
24+
assert [1,2,'a'].pop() == 'a', "list pop failed"
25+
try:
26+
[].pop()
27+
except IndexError:
28+
pass
29+
else:
30+
assert False, "IndexError was not raised"

vm/src/builtins.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -822,6 +822,7 @@ pub fn make_module(ctx: &PyContext) -> PyObjectRef {
822822
);
823823
ctx.set_attr(&py_mod, "TypeError", ctx.exceptions.type_error.clone());
824824
ctx.set_attr(&py_mod, "ValueError", ctx.exceptions.value_error.clone());
825+
ctx.set_attr(&py_mod, "IndexError", ctx.exceptions.index_error.clone());
825826

826827
py_mod
827828
}

vm/src/obj/objlist.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,17 @@ fn list_mul(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
272272
Ok(vm.ctx.new_list(new_elements))
273273
}
274274

275+
fn list_pop(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
276+
arg_check!(vm, args, required = [(zelf, Some(vm.ctx.list_type()))]);
277+
278+
let mut elements = get_mut_elements(zelf);
279+
if let Some(result) = elements.pop() {
280+
Ok(result)
281+
} else {
282+
Err(vm.new_index_error("pop from empty list".to_string()))
283+
}
284+
}
285+
275286
pub fn init(context: &PyContext) {
276287
let ref list_type = context.list_type;
277288
context.set_attr(&list_type, "__add__", context.new_rustfunc(list_add));
@@ -303,4 +314,5 @@ pub fn init(context: &PyContext) {
303314
context.set_attr(&list_type, "index", context.new_rustfunc(list_index));
304315
context.set_attr(&list_type, "reverse", context.new_rustfunc(list_reverse));
305316
context.set_attr(&list_type, "sort", context.new_rustfunc(list_sort));
317+
context.set_attr(&list_type, "pop", context.new_rustfunc(list_pop));
306318
}

0 commit comments

Comments
 (0)