Skip to content

Commit

Permalink
Tidy up examples and PR code
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhewitt committed May 8, 2020
1 parent 2f3d8b8 commit bdf2bb6
Show file tree
Hide file tree
Showing 17 changed files with 92 additions and 105 deletions.
6 changes: 3 additions & 3 deletions examples/rustapi_module/src/datetime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ fn make_time<'p>(
minute,
second,
microsecond,
tzinfo.map(|o| o.to_object(py)),
tzinfo.map(|o| o.as_ref()),
)
}

Expand All @@ -59,7 +59,7 @@ fn time_with_fold<'p>(
minute,
second,
microsecond,
tzinfo.map(|o| o.to_object(py)),
tzinfo.map(|o| o.as_ref()),
fold,
)
}
Expand Down Expand Up @@ -135,7 +135,7 @@ fn make_datetime<'p>(
minute,
second,
microsecond,
tzinfo.map(|o| (o.to_object(py))),
tzinfo.map(|o| o.as_ref()),
)
}

Expand Down
4 changes: 2 additions & 2 deletions examples/rustapi_module/src/objstore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ impl ObjStore {
ObjStore::default()
}

fn push(&mut self, py: Python, obj: &PyObject) {
self.obj.push(obj.to_object(py).into());
fn push(&mut self, obj: &PyObject) {
self.obj.push(obj.into());
}
}

Expand Down
5 changes: 1 addition & 4 deletions src/derive_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
use crate::err::{PyErr, PyResult};
use crate::exceptions::TypeError;
use crate::instance::PyNativeType;
use crate::pyclass::PyClass;
use crate::pyclass_init::PyClassInitializer;
use crate::types::{PyDict, PyModule, PyObject, PyTuple};
Expand Down Expand Up @@ -98,9 +97,7 @@ pub fn parse_fn_args<'p>(
}
// Adjust the remaining args
let args = if accept_args {
let py = args.py();
let slice = args.slice(used_args as isize, nargs as isize);
py.checked_cast_as(slice.as_ref().into()).unwrap()
args.slice(used_args as isize, nargs as isize)
} else {
args
};
Expand Down
8 changes: 4 additions & 4 deletions src/ffi/setobject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,14 @@ pub unsafe fn PyFrozenSet_CheckExact(ob: *mut PyObject) -> c_int {
}

#[inline]
#[cfg_attr(PyPy, link_name = "PyPyObjectSet_CheckExact")]
pub unsafe fn PyObjectSet_CheckExact(ob: *mut PyObject) -> c_int {
#[cfg_attr(PyPy, link_name = "PyPyAnySet_CheckExact")]
pub unsafe fn PyAnySet_CheckExact(ob: *mut PyObject) -> c_int {
(Py_TYPE(ob) == &mut PySet_Type || Py_TYPE(ob) == &mut PyFrozenSet_Type) as c_int
}

#[inline]
pub unsafe fn PyObjectSet_Check(ob: *mut PyObject) -> c_int {
(PyObjectSet_CheckExact(ob) != 0
pub unsafe fn PyAnySet_Check(ob: *mut PyObject) -> c_int {
(PyAnySet_CheckExact(ob) != 0
|| PyType_IsSubtype(Py_TYPE(ob), &mut PySet_Type) != 0
|| PyType_IsSubtype(Py_TYPE(ob), &mut PyFrozenSet_Type) != 0) as c_int
}
Expand Down
2 changes: 1 addition & 1 deletion src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ impl<T> Py<T> {
// }
}

/// Retrieves `&'py` types from `Py<T>` or `Py<PyObject>`.
/// Retrieves `&'py` types from `Py<T>`.
///
/// # Examples
/// `Py<T>::as_ref` returns `&PyDict`, `&PyList` or so for native types, and `&PyCell<T>`
Expand Down
2 changes: 1 addition & 1 deletion src/python.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ impl<'p> Python<'p> {
/// Registers the object in the release pool, and tries to downcast to specific type.
pub fn checked_cast_as<T>(self, obj: Py<PyObject>) -> Result<&'p T, PyDowncastError>
where
T: PyTryFrom<'p>,
T: for<'py> PyTryFrom<'py>,
{
let any: &PyObject = unsafe { self.from_owned_ptr(obj.into_ptr()) };
<T as PyTryFrom>::try_from(any)
Expand Down
5 changes: 2 additions & 3 deletions src/types/boolobject.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// Copyright (c) 2017-present PyO3 Project and Contributors
use crate::{
ffi, AsPyPointer, FromPy, FromPyObject, IntoPy, Py, PyObject, PyResult, PyTryFrom, Python,
ToPyObject,
ffi, AsPyPointer, FromPy, FromPyObject, IntoPy, Py, PyObject, PyResult, Python, ToPyObject,
};

/// Represents a Python `bool`.
Expand Down Expand Up @@ -50,7 +49,7 @@ impl FromPy<bool> for Py<PyObject> {
/// Fails with `TypeError` if the input is not a Python `bool`.
impl<'source> FromPyObject<'source> for bool {
fn extract(obj: &'source PyObject) -> PyResult<Self> {
Ok(<PyBool as PyTryFrom>::try_from(obj)?.is_true())
Ok(obj.downcast::<PyBool>()?.is_true())
}
}

Expand Down
6 changes: 2 additions & 4 deletions src/types/bytes.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
use crate::{
ffi, AsPyPointer, FromPy, FromPyObject, IntoPy, Py, PyObject, PyResult, PyTryFrom, Python,
};
use crate::{ffi, AsPyPointer, FromPy, FromPyObject, IntoPy, Py, PyObject, PyResult, Python};
use std::ops::Index;
use std::os::raw::c_char;
use std::slice::SliceIndex;
Expand Down Expand Up @@ -64,7 +62,7 @@ impl<'a> FromPy<&'a [u8]> for Py<PyObject> {

impl<'a> FromPyObject<'a> for &'a [u8] {
fn extract(obj: &'a PyObject) -> PyResult<Self> {
Ok(<PyBytes as PyTryFrom>::try_from(obj)?.as_bytes())
Ok(obj.downcast::<PyBytes>()?.as_bytes())
}
}
#[cfg(test)]
Expand Down
2 changes: 1 addition & 1 deletion src/types/datetime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ impl PyDateTime {
let timestamp = timestamp.to_object(py);

let time_zone_info = match time_zone_info {
Some(time_zone_info) => time_zone_info.to_object(py),
Some(time_zone_info) => time_zone_info.as_ref(),
None => py.None(),
};

Expand Down
44 changes: 21 additions & 23 deletions src/types/dict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ use crate::instance::PyNativeType;
use crate::types::{PyList, PyObject};
#[cfg(not(PyPy))]
use crate::IntoPyPointer;
use crate::{
ffi, AsPyPointer, FromPyObject, IntoPy, Py, PyTryFrom, Python, ToBorrowedObject, ToPyObject,
};
use crate::{ffi, AsPyPointer, FromPyObject, IntoPy, Py, Python, ToBorrowedObject, ToPyObject};
use std::collections::{BTreeMap, HashMap};
use std::ptr::NonNull;
use std::{cmp, collections, hash};
Expand Down Expand Up @@ -330,7 +328,7 @@ where
S: hash::BuildHasher + Default,
{
fn extract(ob: &'source PyObject) -> Result<Self, PyErr> {
let dict = <PyDict as PyTryFrom>::try_from(ob)?;
let dict: &PyDict = ob.downcast()?;
let mut ret = HashMap::default();
for (k, v) in dict.iter() {
ret.insert(K::extract(k)?, V::extract(v)?);
Expand All @@ -345,7 +343,7 @@ where
V: FromPyObject<'source>,
{
fn extract(ob: &'source PyObject) -> Result<Self, PyErr> {
let dict = <PyDict as PyTryFrom>::try_from(ob)?;
let dict: &PyDict = ob.downcast()?;
let mut ret = BTreeMap::new();
for (k, v) in dict.iter() {
ret.insert(K::extract(k)?, V::extract(v)?);
Expand All @@ -359,7 +357,7 @@ mod test {
use crate::types::dict::IntoPyDict;
use crate::types::{PyDict, PyList, PyTuple};
use crate::Python;
use crate::{PyTryFrom, ToPyObject};
use crate::ToPyObject;
use std::collections::{BTreeMap, HashMap};

#[test]
Expand Down Expand Up @@ -414,11 +412,11 @@ mod test {
let py = gil.python();
let mut v = HashMap::new();
let ob = v.to_object(py);
let dict = <PyDict as PyTryFrom>::try_from(ob).unwrap();
let dict: &PyDict = ob.downcast().unwrap();
assert_eq!(0, dict.len());
v.insert(7, 32);
let ob = v.to_object(py);
let dict2 = <PyDict as PyTryFrom>::try_from(ob).unwrap();
let dict2: &PyDict = ob.downcast().unwrap();
assert_eq!(1, dict2.len());
}

Expand All @@ -429,7 +427,7 @@ mod test {
let mut v = HashMap::new();
v.insert(7, 32);
let ob = v.to_object(py);
let dict = <PyDict as PyTryFrom>::try_from(ob).unwrap();
let dict: &PyDict = ob.downcast().unwrap();
assert_eq!(true, dict.contains(7i32).unwrap());
assert_eq!(false, dict.contains(8i32).unwrap());
}
Expand All @@ -441,7 +439,7 @@ mod test {
let mut v = HashMap::new();
v.insert(7, 32);
let ob = v.to_object(py);
let dict = <PyDict as PyTryFrom>::try_from(ob).unwrap();
let dict: &PyDict = ob.downcast().unwrap();
assert_eq!(32, dict.get_item(7i32).unwrap().extract::<i32>().unwrap());
assert_eq!(None, dict.get_item(8i32));
}
Expand All @@ -453,7 +451,7 @@ mod test {
let mut v = HashMap::new();
v.insert(7, 32);
let ob = v.to_object(py);
let dict = <PyDict as PyTryFrom>::try_from(ob).unwrap();
let dict: &PyDict = ob.downcast().unwrap();
assert!(dict.set_item(7i32, 42i32).is_ok()); // change
assert!(dict.set_item(8i32, 123i32).is_ok()); // insert
assert_eq!(
Expand Down Expand Up @@ -490,7 +488,7 @@ mod test {
let mut v = HashMap::new();
v.insert(7, 32);
let ob = v.to_object(py);
let dict = <PyDict as PyTryFrom>::try_from(ob).unwrap();
let dict: &PyDict = ob.downcast().unwrap();
assert!(dict.set_item(7i32, 42i32).is_ok()); // change
assert!(dict.set_item(8i32, 123i32).is_ok()); // insert
assert_eq!(32i32, v[&7i32]); // not updated!
Expand All @@ -504,7 +502,7 @@ mod test {
let mut v = HashMap::new();
v.insert(7, 32);
let ob = v.to_object(py);
let dict = <PyDict as PyTryFrom>::try_from(ob).unwrap();
let dict: &PyDict = ob.downcast().unwrap();
assert!(dict.del_item(7i32).is_ok());
assert_eq!(0, dict.len());
assert_eq!(None, dict.get_item(7i32));
Expand All @@ -517,7 +515,7 @@ mod test {
let mut v = HashMap::new();
v.insert(7, 32);
let ob = v.to_object(py);
let dict = <PyDict as PyTryFrom>::try_from(ob).unwrap();
let dict: &PyDict = ob.downcast().unwrap();
assert!(dict.del_item(7i32).is_ok()); // change
assert_eq!(32i32, *v.get(&7i32).unwrap()); // not updated!
}
Expand All @@ -531,7 +529,7 @@ mod test {
v.insert(8, 42);
v.insert(9, 123);
let ob = v.to_object(py);
let dict = <PyDict as PyTryFrom>::try_from(ob).unwrap();
let dict: &PyDict = ob.downcast().unwrap();
// Can't just compare against a vector of tuples since we don't have a guaranteed ordering.
let mut key_sum = 0;
let mut value_sum = 0;
Expand All @@ -553,7 +551,7 @@ mod test {
v.insert(8, 42);
v.insert(9, 123);
let ob = v.to_object(py);
let dict = <PyDict as PyTryFrom>::try_from(ob).unwrap();
let dict: &PyDict = ob.downcast().unwrap();
// Can't just compare against a vector of tuples since we don't have a guaranteed ordering.
let mut key_sum = 0;
for el in dict.keys().iter() {
Expand All @@ -571,7 +569,7 @@ mod test {
v.insert(8, 42);
v.insert(9, 123);
let ob = v.to_object(py);
let dict = <PyDict as PyTryFrom>::try_from(ob).unwrap();
let dict: &PyDict = ob.downcast().unwrap();
// Can't just compare against a vector of tuples since we don't have a guaranteed ordering.
let mut values_sum = 0;
for el in dict.values().iter() {
Expand All @@ -589,7 +587,7 @@ mod test {
v.insert(8, 42);
v.insert(9, 123);
let ob = v.to_object(py);
let dict = <PyDict as PyTryFrom>::try_from(ob).unwrap();
let dict: &PyDict = ob.downcast().unwrap();
let mut key_sum = 0;
let mut value_sum = 0;
for (key, value) in dict.iter() {
Expand All @@ -609,7 +607,7 @@ mod test {
v.insert(8, 42);
v.insert(9, 123);
let ob = v.to_object(py);
let dict = <PyDict as PyTryFrom>::try_from(ob).unwrap();
let dict: &PyDict = ob.downcast().unwrap();
let mut key_sum = 0;
let mut value_sum = 0;
for (key, value) in dict {
Expand All @@ -629,7 +627,7 @@ mod test {
map.insert(1, 1);

let m = map.to_object(py);
let py_map = <PyDict as PyTryFrom>::try_from(m).unwrap();
let py_map: &PyDict = m.downcast().unwrap();

assert!(py_map.len() == 1);
assert!(py_map.get_item(1).unwrap().extract::<i32>().unwrap() == 1);
Expand All @@ -645,7 +643,7 @@ mod test {
map.insert(1, 1);

let m = map.to_object(py);
let py_map = <PyDict as PyTryFrom>::try_from(m).unwrap();
let py_map: &PyDict = m.downcast().unwrap();

assert!(py_map.len() == 1);
assert!(py_map.get_item(1).unwrap().extract::<i32>().unwrap() == 1);
Expand All @@ -661,7 +659,7 @@ mod test {
map.insert(1, 1);

let m = map.to_object(py);
let py_map = <PyDict as PyTryFrom>::try_from(m).unwrap();
let py_map: &PyDict = m.downcast().unwrap();

assert!(py_map.len() == 1);
assert!(py_map.get_item(1).unwrap().extract::<i32>().unwrap() == 1);
Expand Down Expand Up @@ -690,7 +688,7 @@ mod test {
map.insert(1, 1);

let m = map.to_object(py);
let py_map = <PyDict as PyTryFrom>::try_from(m).unwrap();
let py_map: &PyDict = m.downcast().unwrap();

assert!(py_map.len() == 1);
assert!(py_map.get_item(1).unwrap().extract::<i32>().unwrap() == 1);
Expand Down
Loading

0 comments on commit bdf2bb6

Please sign in to comment.