Skip to content

Commit 685a7e8

Browse files
authored
Merge pull request RustPython#4466 from moreal/array-contains
Implement `array.array.__contains__`
2 parents bdd3beb + a866d88 commit 685a7e8

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

extra_tests/snippets/stdlib_array.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,3 +112,8 @@ def test_array_frombytes():
112112
# test arrayiterator name
113113
i = iter(a)
114114
assert str(i.__class__.__name__) == "arrayiterator"
115+
116+
# teset array.__contains__
117+
a = array('B', [0])
118+
assert a.__contains__(0)
119+
assert not a.__contains__(1)

stdlib/src/array.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1160,6 +1160,23 @@ mod array {
11601160
zelf.as_object().dict(),
11611161
))
11621162
}
1163+
1164+
#[pymethod(magic)]
1165+
fn contains(&self, value: PyObjectRef, vm: &VirtualMachine) -> bool {
1166+
let array = self.array.read();
1167+
for element in array
1168+
.iter(vm)
1169+
.map(|x| x.expect("Expected to be checked by array.len() and read lock."))
1170+
{
1171+
if let Ok(true) =
1172+
element.rich_compare_bool(value.as_object(), PyComparisonOp::Eq, vm)
1173+
{
1174+
return true;
1175+
}
1176+
}
1177+
1178+
false
1179+
}
11631180
}
11641181

11651182
impl Comparable for PyArray {

0 commit comments

Comments
 (0)