Skip to content

Commit

Permalink
Fix conversion of non-mapping sequences into PyMapping (i.e PyStr
Browse files Browse the repository at this point in the history
… can be cast to `PyMapping`) due to `PyMapping_Check` returning true for sequences.
  • Loading branch information
aviramha committed Jan 13, 2022
1 parent edf03c1 commit ba0b92e
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Fix undefined behavior in `PySlice::indices`. [#2061](https://github.com/PyO3/pyo3/pull/2061)
- Use the Rust function path for `wrap_pymodule!` of a `#[pymodule]` with a `#[pyo3(name = "..")]` attribute, not the Python name. [#2081](https://github.com/PyO3/pyo3/pull/2081)
- Fix panic in `#[pyfunction]` generated code when a required argument following an `Option` was not provided. [#2093](https://github.com/PyO3/pyo3/pull/2093)
- Fix conversion of non-mapping sequences into `PyMapping` (i.e `PyStr` can be cast to `PyMapping`) due to `PyMapping_Check` returning true for sequences. [#2098](https://github.com/PyO3/pyo3/pull/2098)

## [0.15.1] - 2021-11-19

Expand Down
16 changes: 13 additions & 3 deletions src/types/mapping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,9 @@ impl<'v> PyTryFrom<'v> for PyMapping {
fn try_from<V: Into<&'v PyAny>>(value: V) -> Result<&'v PyMapping, PyDowncastError<'v>> {
let value = value.into();
unsafe {
if ffi::PyMapping_Check(value.as_ptr()) != 0 {
if ffi::PyMapping_Check(value.as_ptr()) != 0
&& ffi::PySequence_Check(value.as_ptr()) == 0
{
Ok(<PyMapping as PyTryFrom>::try_from_unchecked(value))
} else {
Err(PyDowncastError::new(value, "Mapping"))
Expand Down Expand Up @@ -142,8 +144,8 @@ mod tests {
use std::collections::HashMap;

use crate::{
exceptions::PyKeyError,
types::{PyDict, PyTuple},
exceptions::{PyKeyError, PyTypeError},
types::{PyDict, PyString, PyTuple},
Python,
};

Expand Down Expand Up @@ -299,4 +301,12 @@ mod tests {
assert_eq!(mapping_ref.get_refcnt(), 2);
})
}

#[test]
fn test_not_mapping() {
Python::with_gil(|py| {
let str = PyString::new(py, "hello, world");
str.downcast::<PyMapping>().unwrap_err();
});
}
}

0 comments on commit ba0b92e

Please sign in to comment.