Skip to content

Commit

Permalink
Add Mapping::contains (#2133)
Browse files Browse the repository at this point in the history
* Add Mapping::contains

* Fix typo

* Add a changelog entry

* Use PyAny::contatins instead

* Update mapping.rs
  • Loading branch information
Gobot1234 committed Feb 6, 2022
1 parent 1ea3463 commit b2f9e28
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Add check for correct number of arguments on magic methods. [#2083](https://github.com/PyO3/pyo3/pull/2083)
- `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)
- Add `PyAny::contains` method (`in` operator for `PyAny`). [#2115](https://github.com/PyO3/pyo3/pull/2115)
- Add `PyMapping::contains` method (`in` operator for `PyMapping`). [#2133](https://github.com/PyO3/pyo3/pull/2133)

### Changed

Expand Down
25 changes: 25 additions & 0 deletions src/types/mapping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,16 @@ impl PyMapping {
self.len().map(|l| l == 0)
}

/// Determines if the mapping contains the specified key.
///
/// This is equivalent to the Python expression `key in self`.
pub fn contains<K>(&self, key: K) -> PyResult<bool>
where
K: ToBorrowedObject,
{
PyAny::contains(self, key)
}

/// Gets the item in self with key `key`.
///
/// Returns an `Err` if the item with specified key is not found, usually `KeyError`.
Expand Down Expand Up @@ -166,6 +176,21 @@ mod tests {
});
}

#[test]
fn test_contains() {
Python::with_gil(|py| {
let mut v = HashMap::new();
v.insert("key0", 1234);
let ob = v.to_object(py);
let mapping = <PyMapping as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
mapping.set_item("key1", "foo").unwrap();

assert!(mapping.contains("key0").unwrap());
assert!(mapping.contains("key1").unwrap());
assert!(!mapping.contains("key2").unwrap());
});
}

#[test]
fn test_get_item() {
Python::with_gil(|py| {
Expand Down

0 comments on commit b2f9e28

Please sign in to comment.