Skip to content

Commit b2f9e28

Browse files
authored
Add Mapping::contains (#2133)
* Add Mapping::contains * Fix typo * Add a changelog entry * Use PyAny::contatins instead * Update mapping.rs
1 parent 1ea3463 commit b2f9e28

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
3030
- Add check for correct number of arguments on magic methods. [#2083](https://github.com/PyO3/pyo3/pull/2083)
3131
- `wrap_pyfunction!` can now wrap a `#[pyfunction]` which is implemented in a different Rust module or crate. [#2091](https://github.com/PyO3/pyo3/pull/2091)
3232
- Add `PyAny::contains` method (`in` operator for `PyAny`). [#2115](https://github.com/PyO3/pyo3/pull/2115)
33+
- Add `PyMapping::contains` method (`in` operator for `PyMapping`). [#2133](https://github.com/PyO3/pyo3/pull/2133)
3334

3435
### Changed
3536

src/types/mapping.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,16 @@ impl PyMapping {
3333
self.len().map(|l| l == 0)
3434
}
3535

36+
/// Determines if the mapping contains the specified key.
37+
///
38+
/// This is equivalent to the Python expression `key in self`.
39+
pub fn contains<K>(&self, key: K) -> PyResult<bool>
40+
where
41+
K: ToBorrowedObject,
42+
{
43+
PyAny::contains(self, key)
44+
}
45+
3646
/// Gets the item in self with key `key`.
3747
///
3848
/// Returns an `Err` if the item with specified key is not found, usually `KeyError`.
@@ -166,6 +176,21 @@ mod tests {
166176
});
167177
}
168178

179+
#[test]
180+
fn test_contains() {
181+
Python::with_gil(|py| {
182+
let mut v = HashMap::new();
183+
v.insert("key0", 1234);
184+
let ob = v.to_object(py);
185+
let mapping = <PyMapping as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
186+
mapping.set_item("key1", "foo").unwrap();
187+
188+
assert!(mapping.contains("key0").unwrap());
189+
assert!(mapping.contains("key1").unwrap());
190+
assert!(!mapping.contains("key2").unwrap());
191+
});
192+
}
193+
169194
#[test]
170195
fn test_get_item() {
171196
Python::with_gil(|py| {

0 commit comments

Comments
 (0)