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 Apr 26, 2020
1 parent a566b8d commit 841408b
Show file tree
Hide file tree
Showing 18 changed files with 97 additions and 108 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 @@ -278,7 +278,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
6 changes: 3 additions & 3 deletions src/objectprotocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -497,14 +497,14 @@ mod test {
use super::*;
use crate::types::{IntoPyDict, PyString};
use crate::Python;
use crate::{PyTryFrom, ToPyObject};
use crate::ToPyObject;

#[test]
fn test_debug_string() {
let gil = Python::acquire_gil();
let py = gil.python();
let v = "Hello\n".to_object(py);
let s = <PyString as PyTryFrom>::try_from(v).unwrap();
let s: &PyString = v.downcast().unwrap();
assert_eq!(format!("{:?}", s), "'Hello\\n'");
}

Expand All @@ -513,7 +513,7 @@ mod test {
let gil = Python::acquire_gil();
let py = gil.python();
let v = "Hello\n".to_object(py);
let s = <PyString as PyTryFrom>::try_from(v).unwrap();
let s: &PyString = v.downcast().unwrap();
assert_eq!(format!("{}", s), "Hello\n");
}

Expand Down
4 changes: 2 additions & 2 deletions src/python.rs
Original file line number Diff line number Diff line change
Expand Up @@ -290,10 +290,10 @@ 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 obj = unsafe { gil::register_owned(self, obj.into_non_null()) };
<T as PyTryFrom>::try_from(obj)
obj.downcast()
}

/// Registers the object in the release pool, and does an unchecked downcast
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
42 changes: 21 additions & 21 deletions src/types/dict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ use crate::err::{self, PyErr, PyResult};
use crate::instance::PyNativeType;
use crate::types::{PyList, PyObject};
use crate::AsPyPointer;
use crate::FromPyObject;
#[cfg(not(PyPy))]
use crate::IntoPyPointer;
use crate::Python;
use crate::{ffi, IntoPy, Py};
use crate::{FromPyObject, PyTryFrom};
use crate::{ToBorrowedObject, ToPyObject};
use std::collections::{BTreeMap, HashMap};
use std::{cmp, collections, hash};
Expand Down Expand Up @@ -324,7 +324,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 @@ -339,7 +339,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 @@ -354,7 +354,7 @@ mod test {
use crate::types::{PyDict, PyList, PyTuple};
use crate::ObjectProtocol;
use crate::Python;
use crate::{PyTryFrom, ToPyObject};
use crate::ToPyObject;
use std::collections::{BTreeMap, HashMap};

#[test]
Expand Down Expand Up @@ -409,11 +409,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 @@ -424,7 +424,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 @@ -436,7 +436,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 @@ -448,7 +448,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 @@ -485,7 +485,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 @@ -499,7 +499,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 @@ -512,7 +512,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 @@ -526,7 +526,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 @@ -548,7 +548,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 @@ -566,7 +566,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 @@ -584,7 +584,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 @@ -604,7 +604,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 @@ -624,7 +624,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 @@ -640,7 +640,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 @@ -656,7 +656,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 @@ -685,7 +685,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 841408b

Please sign in to comment.