Skip to content

Commit 7cf2544

Browse files
committed
Add set.__iter__
1 parent c22fb58 commit 7cf2544

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

tests/snippets/set.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,13 @@ def __hash__(self):
9999
assert a == set([1,2,3,4,5])
100100
assert_raises(TypeError, lambda: a.update(1))
101101

102+
a = set([1,2,3])
103+
b = set()
104+
for e in a:
105+
assert e == 1 or e == 2 or e == 3
106+
b.add(e)
107+
assert a == b
108+
102109
a = set([1,2,3])
103110
a.intersection_update([2,3,4,5])
104111
assert a == set([2,3])

vm/src/obj/objset.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -521,6 +521,22 @@ fn set_symmetric_difference_update(vm: &mut VirtualMachine, args: PyFuncArgs) ->
521521
}
522522
}
523523

524+
fn set_iter(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
525+
arg_check!(vm, args, required = [(zelf, Some(vm.ctx.set_type()))]);
526+
527+
let items = get_elements(zelf).values().map(|x| x.clone()).collect();
528+
let set_list = vm.ctx.new_list(items);
529+
let iter_obj = PyObject::new(
530+
PyObjectPayload::Iterator {
531+
position: 0,
532+
iterated_obj: set_list,
533+
},
534+
vm.ctx.iter_type(),
535+
);
536+
537+
Ok(iter_obj)
538+
}
539+
524540
fn frozenset_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
525541
arg_check!(vm, args, required = [(o, Some(vm.ctx.frozenset_type()))]);
526542

@@ -608,6 +624,7 @@ pub fn init(context: &PyContext) {
608624
"symmetric_difference_update",
609625
context.new_rustfunc(set_symmetric_difference_update),
610626
);
627+
context.set_attr(&set_type, "__iter__", context.new_rustfunc(set_iter));
611628

612629
let frozenset_type = &context.frozenset_type;
613630

0 commit comments

Comments
 (0)