Skip to content

Commit ecfc70e

Browse files
committed
Add list.copy()
1 parent e5af4ca commit ecfc70e

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

tests/snippets/list.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,3 +67,11 @@
6767
pass
6868
else:
6969
assert False, "OverflowError was not raised"
70+
71+
x = [[], 2, {}]
72+
y = x.copy()
73+
assert x is not y
74+
assert x == y
75+
assert all(a is b for a, b in zip(x, y))
76+
y.append(4)
77+
assert x != y

vm/src/obj/objlist.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,12 @@ fn list_clear(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
219219
Ok(vm.get_none())
220220
}
221221

222+
fn list_copy(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
223+
arg_check!(vm, args, required = [(zelf, Some(vm.ctx.list_type()))]);
224+
let elements = get_elements(zelf);
225+
Ok(vm.ctx.new_list(elements.clone()))
226+
}
227+
222228
fn list_count(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
223229
arg_check!(
224230
vm,
@@ -439,6 +445,7 @@ pub fn init(context: &PyContext) {
439445
context.set_attr(&list_type, "__doc__", context.new_str(list_doc.to_string()));
440446
context.set_attr(&list_type, "append", context.new_rustfunc(list_append));
441447
context.set_attr(&list_type, "clear", context.new_rustfunc(list_clear));
448+
context.set_attr(&list_type, "copy", context.new_rustfunc(list_copy));
442449
context.set_attr(&list_type, "count", context.new_rustfunc(list_count));
443450
context.set_attr(&list_type, "extend", context.new_rustfunc(list_extend));
444451
context.set_attr(&list_type, "index", context.new_rustfunc(list_index));

0 commit comments

Comments
 (0)