Use Python::get_type() instead of PyTypeInfo::type_object()

The former needs one less import and uses a familiar object.
This commit is contained in:
Georg Brandl 2022-11-19 09:17:40 +01:00
parent 21fd1a91d0
commit 99c8dea30e
12 changed files with 31 additions and 41 deletions

View File

@ -2,7 +2,7 @@ use crate::{
exceptions::{PyBaseException, PyTypeError},
ffi,
types::{PyTraceback, PyType},
AsPyPointer, IntoPy, IntoPyPointer, Py, PyObject, PyTypeInfo, Python,
AsPyPointer, IntoPy, IntoPyPointer, Py, PyObject, Python,
};
#[derive(Clone)]
@ -89,7 +89,7 @@ impl PyErrState {
#[inline]
pub(crate) fn exceptions_must_derive_from_base_exception(py: Python<'_>) -> Self {
PyErrState::LazyValue {
ptype: PyTypeError::type_object(py).into(),
ptype: py.get_type::<PyTypeError>().into(),
pvalue: boxed_args("exceptions must derive from BaseException"),
}
}

View File

@ -484,16 +484,14 @@ impl PyErr {
///
/// The `category` should be one of the `Warning` classes available in
/// [`pyo3::exceptions`](crate::exceptions), or a subclass. The Python
/// object can be retrieved using [`PyTypeInfo::type_object()`].
/// object can be retrieved using [`Python::get_type()`].
///
/// Example:
/// ```rust
/// use pyo3::prelude::*;
/// use pyo3::PyTypeInfo;
///
/// # use pyo3::prelude::*;
/// # fn main() -> PyResult<()> {
/// Python::with_gil(|py| {
/// let user_warning = pyo3::exceptions::PyUserWarning::type_object(py);
/// let user_warning = py.get_type::<pyo3::exceptions::PyUserWarning>();
/// PyErr::warn(py, user_warning, "I am warning you", 0)?;
/// Ok(())
/// })
@ -833,7 +831,7 @@ fn exceptions_must_derive_from_base_exception(py: Python<'_>) -> PyErr {
mod tests {
use super::PyErrState;
use crate::exceptions;
use crate::{AsPyPointer, PyErr, PyTypeInfo, Python};
use crate::{AsPyPointer, PyErr, Python};
#[test]
fn no_error() {
@ -1009,7 +1007,7 @@ mod tests {
// GIL locked should prevent effects to be visible to other testing
// threads.
Python::with_gil(|py| {
let cls = exceptions::PyUserWarning::type_object(py);
let cls = py.get_type::<exceptions::PyUserWarning>();
// Reset warning filter to default state
let warnings = py.import("warnings").unwrap();

View File

@ -3,7 +3,7 @@ use crate::{
ffi,
pyclass::boolean_struct::False,
types::{PyDict, PyString, PyTuple},
FromPyObject, PyAny, PyClass, PyErr, PyRef, PyRefMut, PyResult, PyTypeInfo, Python,
FromPyObject, PyAny, PyClass, PyErr, PyRef, PyRefMut, PyResult, Python,
};
/// A trait which is used to help PyO3 macros extract function arguments.
@ -167,7 +167,7 @@ pub fn from_py_with_with_default<'py, T>(
#[doc(hidden)]
#[cold]
pub fn argument_extraction_error(py: Python<'_>, arg_name: &str, error: PyErr) -> PyErr {
if error.get_type(py).is(PyTypeError::type_object(py)) {
if error.get_type(py).is(py.get_type::<PyTypeError>()) {
let remapped_error =
PyTypeError::new_err(format!("argument '{}': {}", arg_name, error.value(py)));
remapped_error.set_cause(py, error.cause(py));

View File

@ -596,6 +596,7 @@ impl<'py> Python<'py> {
}
/// Gets the Python type object for type `T`.
#[inline]
pub fn get_type<T>(self) -> &'py PyType
where
T: PyTypeInfo,

View File

@ -913,7 +913,6 @@ impl PyAny {
#[cfg(test)]
mod tests {
use crate::{
type_object::PyTypeInfo,
types::{IntoPyDict, PyList, PyLong, PyModule},
Python, ToPyObject,
};
@ -1014,7 +1013,7 @@ class SimpleClass:
fn test_any_isinstance() {
Python::with_gil(|py| {
let l = vec![1u8, 2].to_object(py).into_ref(py);
assert!(l.is_instance(PyList::type_object(py)).unwrap());
assert!(l.is_instance(py.get_type::<PyList>()).unwrap());
});
}

View File

@ -421,7 +421,7 @@ mod tests {
#[cfg(not(PyPy))]
use crate::exceptions;
#[cfg(not(PyPy))]
use crate::{types::PyList, PyTypeInfo};
use crate::types::PyList;
use crate::{types::PyTuple, Python, ToPyObject};
use std::collections::{BTreeMap, HashMap};
@ -886,7 +886,7 @@ mod tests {
Python::with_gil(|py| {
let dict = abc_dict(py);
let keys = dict.call_method0("keys").unwrap();
assert!(keys.is_instance(PyDictKeys::type_object(py)).unwrap());
assert!(keys.is_instance(py.get_type::<PyDictKeys>()).unwrap());
})
}
@ -896,7 +896,7 @@ mod tests {
Python::with_gil(|py| {
let dict = abc_dict(py);
let values = dict.call_method0("values").unwrap();
assert!(values.is_instance(PyDictValues::type_object(py)).unwrap());
assert!(values.is_instance(py.get_type::<PyDictValues>()).unwrap());
})
}
@ -906,7 +906,7 @@ mod tests {
Python::with_gil(|py| {
let dict = abc_dict(py);
let items = dict.call_method0("items").unwrap();
assert!(items.is_instance(PyDictItems::type_object(py)).unwrap());
assert!(items.is_instance(py.get_type::<PyDictItems>()).unwrap());
})
}
}

View File

@ -1,5 +1,4 @@
use crate::ffi;
use crate::type_object::PyTypeInfo;
use crate::types::PyType;
use crate::{PyAny, PyResult};
@ -54,7 +53,7 @@ impl PySuper {
/// ```
pub fn new<'py>(ty: &'py PyType, obj: &'py PyAny) -> PyResult<&'py PySuper> {
let py = ty.py();
let super_ = PySuper::type_object(py).call1((ty, obj))?;
let super_ = py.get_type::<PySuper>().call1((ty, obj))?;
let super_ = super_.downcast::<PySuper>()?;
Ok(super_)
}

View File

@ -282,8 +282,6 @@ impl PyString {
#[cfg(test)]
mod tests {
use super::*;
#[cfg(all(not(Py_LIMITED_API), target_endian = "little"))]
use crate::PyTypeInfo;
use crate::Python;
use crate::{PyObject, ToPyObject};
#[cfg(all(not(Py_LIMITED_API), target_endian = "little"))]
@ -379,7 +377,7 @@ mod tests {
let data = unsafe { s.data().unwrap() };
assert_eq!(data, PyStringData::Ucs1(b"f\xfe"));
let err = data.to_string(py).unwrap_err();
assert!(err.get_type(py).is(PyUnicodeDecodeError::type_object(py)));
assert!(err.get_type(py).is(py.get_type::<PyUnicodeDecodeError>()));
assert!(err
.to_string()
.contains("'utf-8' codec can't decode byte 0xfe in position 1"));
@ -421,7 +419,7 @@ mod tests {
let data = unsafe { s.data().unwrap() };
assert_eq!(data, PyStringData::Ucs2(&[0xff22, 0xd800]));
let err = data.to_string(py).unwrap_err();
assert!(err.get_type(py).is(PyUnicodeDecodeError::type_object(py)));
assert!(err.get_type(py).is(py.get_type::<PyUnicodeDecodeError>()));
assert!(err
.to_string()
.contains("'utf-16' codec can't decode bytes in position 0-3"));
@ -460,7 +458,7 @@ mod tests {
let data = unsafe { s.data().unwrap() };
assert_eq!(data, PyStringData::Ucs4(&[0x20000, 0xd800]));
let err = data.to_string(py).unwrap_err();
assert!(err.get_type(py).is(PyUnicodeDecodeError::type_object(py)));
assert!(err.get_type(py).is(py.get_type::<PyUnicodeDecodeError>()));
assert!(err
.to_string()
.contains("'utf-32' codec can't decode bytes in position 0-7"));

View File

@ -75,16 +75,14 @@ impl PyType {
#[cfg(test)]
mod tests {
use crate::{
types::{PyBool, PyLong},
PyTypeInfo, Python,
};
use crate::types::{PyBool, PyLong};
use crate::Python;
#[test]
fn test_type_is_subclass() {
Python::with_gil(|py| {
let bool_type = PyBool::type_object(py);
let long_type = PyLong::type_object(py);
let bool_type = py.get_type::<PyBool>();
let long_type = py.get_type::<PyLong>();
assert!(bool_type.is_subclass(long_type).unwrap());
});
}
@ -92,7 +90,7 @@ mod tests {
#[test]
fn test_type_is_subclass_of() {
Python::with_gil(|py| {
assert!(PyBool::type_object(py).is_subclass_of::<PyLong>().unwrap());
assert!(py.get_type::<PyBool>().is_subclass_of::<PyLong>().unwrap());
});
}

View File

@ -3,7 +3,6 @@
use pyo3::class::PyTraverseError;
use pyo3::class::PyVisit;
use pyo3::prelude::*;
use pyo3::PyTypeInfo;
use pyo3::{py_run, AsPyPointer, PyCell, PyTryInto};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
@ -228,7 +227,7 @@ fn gc_during_borrow() {
}
// get the traverse function
let ty = TraversableClass::type_object(py).as_type_ptr();
let ty = py.get_type::<TraversableClass>().as_type_ptr();
let traverse = get_type_traverse(ty).unwrap();
// create an object and check that traversing it works normally
@ -284,7 +283,7 @@ fn traverse_error() {
}
// get the traverse function
let ty = PanickyTraverse::type_object(py).as_type_ptr();
let ty = py.get_type::<PanickyTraverse>().as_type_ptr();
let traverse = get_type_traverse(ty).unwrap();
// confirm that traversing errors

View File

@ -1,7 +1,7 @@
#![cfg(feature = "macros")]
use pyo3::prelude::*;
use pyo3::{py_run, PyTypeInfo};
use pyo3::py_run;
use pyo3::types::IntoPyDict;
@ -107,8 +107,8 @@ fn mutation_fails() {
#[test]
fn is_subclass_and_is_instance() {
Python::with_gil(|py| {
let sub_ty = SubClass::type_object(py);
let base_ty = BaseClass::type_object(py);
let sub_ty = py.get_type::<SubClass>();
let base_ty = py.get_type::<BaseClass>();
assert!(sub_ty.is_subclass_of::<BaseClass>().unwrap());
assert!(sub_ty.is_subclass(base_ty).unwrap());
@ -308,10 +308,9 @@ impl SimpleClass {
#[test]
fn test_subclass_ref_counts() {
// regression test for issue #1363
use pyo3::PyTypeInfo;
Python::with_gil(|py| {
#[allow(non_snake_case)]
let SimpleClass = SimpleClass::type_object(py);
let SimpleClass = py.get_type::<SimpleClass>();
py_run!(
py,
SimpleClass,

View File

@ -2,7 +2,6 @@
use pyo3::prelude::*;
use pyo3::types::PyType;
use pyo3::PyTypeInfo;
#[macro_use]
mod common;
@ -65,7 +64,7 @@ impl PyClassWithMultiplePyMethods {
#[test]
fn test_class_with_multiple_pymethods() {
Python::with_gil(|py| {
let cls = PyClassWithMultiplePyMethods::type_object(py);
let cls = py.get_type::<PyClassWithMultiplePyMethods>();
py_assert!(py, cls, "cls()() == 'call'");
py_assert!(py, cls, "cls().method() == 'method'");
py_assert!(py, cls, "cls.classmethod() == 'classmethod'");