Skip to content

Commit b18156a

Browse files
committed
Added set object membership test
1 parent 2f29798 commit b18156a

2 files changed

Lines changed: 24 additions & 3 deletions

File tree

tests/snippets/membership.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,8 @@
1919
assert 3 not in (1, 2)
2020

2121
# test set
22-
# TODO: uncomment this when sets are implemented
23-
# assert 1 in set(1, 2)
24-
# assert 3 not in set(1, 2)
22+
assert 1 in set([1, 2])
23+
assert 3 not in set([1, 2])
2524

2625
# test dicts
2726
# TODO: test dicts when keys other than strings will be allowed

vm/src/obj/objset.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use super::super::pyobject::{
77
PyResult, TypeProtocol,
88
};
99
use super::super::vm::VirtualMachine;
10+
use super::objbool;
1011
use super::objiter;
1112
use super::objstr;
1213
use super::objtype;
@@ -88,8 +89,29 @@ fn set_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
8889
Ok(vm.new_str(s))
8990
}
9091

92+
pub fn set_contains(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
93+
arg_check!(
94+
vm,
95+
args,
96+
required = [(set, Some(vm.ctx.set_type())), (needle, None)]
97+
);
98+
for element in get_elements(set).iter() {
99+
match vm.call_method(needle, "__eq__", vec![element.1.clone()]) {
100+
Ok(value) => {
101+
if objbool::get_value(&value) {
102+
return Ok(vm.new_bool(true));
103+
}
104+
}
105+
Err(_) => return Err(vm.new_type_error("".to_string())),
106+
}
107+
}
108+
109+
Ok(vm.new_bool(false))
110+
}
111+
91112
pub fn init(context: &PyContext) {
92113
let ref set_type = context.set_type;
114+
set_type.set_attr("__contains__", context.new_rustfunc(set_contains));
93115
set_type.set_attr("__len__", context.new_rustfunc(set_len));
94116
set_type.set_attr("__new__", context.new_rustfunc(set_new));
95117
set_type.set_attr("__repr__", context.new_rustfunc(set_repr));

0 commit comments

Comments
 (0)