Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Mapping::contains #2133

Merged
merged 6 commits into from
Feb 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,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