Skip to content

Commit a89b059

Browse files
committed
Add set.pop
1 parent e2ee933 commit a89b059

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

tests/snippets/set.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,3 +86,10 @@ def __hash__(self):
8686
b.clear()
8787
assert len(a) == 3
8888
assert len(b) == 0
89+
90+
a = set([1,2])
91+
b = a.pop()
92+
assert b in [1,2]
93+
c = a.pop()
94+
assert (c in [1,2] and c != b)
95+
assert_raises(KeyError, lambda: a.pop())

vm/src/obj/objset.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -418,6 +418,20 @@ fn set_combine_inner(
418418
))
419419
}
420420

421+
fn set_pop(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
422+
arg_check!(vm, args, required = [(s, Some(vm.ctx.set_type()))]);
423+
424+
let mut mut_obj = s.borrow_mut();
425+
426+
match mut_obj.payload {
427+
PyObjectPayload::Set { ref mut elements } => match elements.clone().keys().next() {
428+
Some(key) => Ok(elements.remove(key).unwrap()),
429+
None => Err(vm.new_key_error("pop from an empty set".to_string())),
430+
},
431+
_ => Err(vm.new_type_error("".to_string())),
432+
}
433+
}
434+
421435
fn frozenset_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
422436
arg_check!(vm, args, required = [(o, Some(vm.ctx.frozenset_type()))]);
423437

@@ -488,6 +502,7 @@ pub fn init(context: &PyContext) {
488502
context.set_attr(&set_type, "discard", context.new_rustfunc(set_discard));
489503
context.set_attr(&set_type, "clear", context.new_rustfunc(set_clear));
490504
context.set_attr(&set_type, "copy", context.new_rustfunc(set_copy));
505+
context.set_attr(&set_type, "pop", context.new_rustfunc(set_pop));
491506

492507
let frozenset_type = &context.frozenset_type;
493508

0 commit comments

Comments
 (0)