diff --git a/tests/snippets/list.py b/tests/snippets/list.py index 85010a755..709b6ff71 100644 --- a/tests/snippets/list.py +++ b/tests/snippets/list.py @@ -20,3 +20,11 @@ except ValueError: pass else: assert False, "ValueError was not raised" + +assert [1,2,'a'].pop() == 'a', "list pop failed" +try: + [].pop() +except IndexError: + pass +else: + assert False, "IndexError was not raised" diff --git a/vm/src/builtins.rs b/vm/src/builtins.rs index f1067d81e..d823e9205 100644 --- a/vm/src/builtins.rs +++ b/vm/src/builtins.rs @@ -822,6 +822,7 @@ pub fn make_module(ctx: &PyContext) -> PyObjectRef { ); ctx.set_attr(&py_mod, "TypeError", ctx.exceptions.type_error.clone()); ctx.set_attr(&py_mod, "ValueError", ctx.exceptions.value_error.clone()); + ctx.set_attr(&py_mod, "IndexError", ctx.exceptions.index_error.clone()); py_mod } diff --git a/vm/src/obj/objlist.rs b/vm/src/obj/objlist.rs index 641bb9aa6..9f69792bc 100644 --- a/vm/src/obj/objlist.rs +++ b/vm/src/obj/objlist.rs @@ -272,6 +272,17 @@ fn list_mul(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.ctx.new_list(new_elements)) } +fn list_pop(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { + arg_check!(vm, args, required = [(zelf, Some(vm.ctx.list_type()))]); + + let mut elements = get_mut_elements(zelf); + if let Some(result) = elements.pop() { + Ok(result) + } else { + Err(vm.new_index_error("pop from empty list".to_string())) + } +} + pub fn init(context: &PyContext) { let ref list_type = context.list_type; context.set_attr(&list_type, "__add__", context.new_rustfunc(list_add)); @@ -303,4 +314,5 @@ pub fn init(context: &PyContext) { context.set_attr(&list_type, "index", context.new_rustfunc(list_index)); context.set_attr(&list_type, "reverse", context.new_rustfunc(list_reverse)); context.set_attr(&list_type, "sort", context.new_rustfunc(list_sort)); + context.set_attr(&list_type, "pop", context.new_rustfunc(list_pop)); }