Merge pull request #388 from kngwyu/pyany

Rename PyObjectRef with PyAny
This commit is contained in:
konstin 2019-03-18 11:04:29 +01:00 committed by GitHub
commit 3e475b052b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
38 changed files with 269 additions and 258 deletions

View File

@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
### Changed
* Renamed `PyObjectRef` to `PyAny` in #388
* Renamed `add_function` to `add_wrapped` as it now also supports modules.
* Renamed `#[pymodinit]` to `#[pymodule]`
* `py.init(|| value)` becomes `Py::new(value)`

View File

@ -37,7 +37,7 @@ impl Default for PyClassArgs {
// We need the 0 as value for the constant we're later building using quote for when there
// are no other flags
flags: vec![parse_quote! {0}],
base: parse_quote! {pyo3::types::PyObjectRef},
base: parse_quote! {pyo3::types::PyAny},
}
}
}

View File

@ -20,7 +20,7 @@
use crate::err::{self, PyResult};
use crate::exceptions;
use crate::ffi;
use crate::types::PyObjectRef;
use crate::types::PyAny;
use crate::AsPyPointer;
use crate::Python;
use libc;
@ -163,7 +163,7 @@ fn validate(b: &ffi::Py_buffer) {
impl PyBuffer {
/// Get the underlying buffer from the specified python object.
pub fn get(py: Python, obj: &PyObjectRef) -> PyResult<PyBuffer> {
pub fn get(py: Python, obj: &PyAny) -> PyResult<PyBuffer> {
unsafe {
let mut buf = Box::new(mem::zeroed::<ffi::Py_buffer>());
err::error_on_minusone(

View File

@ -15,7 +15,7 @@ use crate::exceptions;
use crate::ffi;
use crate::objectprotocol::ObjectProtocol;
use crate::type_object::PyTypeInfo;
use crate::types::PyObjectRef;
use crate::types::PyAny;
use crate::IntoPyPointer;
use crate::Python;
use crate::{FromPyObject, IntoPyObject};
@ -440,7 +440,7 @@ where
let _pool = crate::GILPool::new();
let py = Python::assume_gil_acquired();
let slf = py.from_borrowed_ptr::<T>(slf);
let arg = py.from_borrowed_ptr::<PyObjectRef>(arg);
let arg = py.from_borrowed_ptr::<PyAny>(arg);
let res = match extract_op(op) {
Ok(op) => match arg.extract() {

View File

@ -10,35 +10,35 @@ use crate::class::methods::PyMethodDef;
use crate::err::PyResult;
use crate::ffi;
use crate::type_object::PyTypeInfo;
use crate::types::{PyObjectRef, PyType};
use crate::types::{PyAny, PyType};
use crate::{FromPyObject, IntoPyObject};
use std::os::raw::c_int;
/// Descriptor interface
#[allow(unused_variables)]
pub trait PyDescrProtocol<'p>: PyTypeInfo {
fn __get__(&'p self, instance: &'p PyObjectRef, owner: Option<&'p PyType>) -> Self::Result
fn __get__(&'p self, instance: &'p PyAny, owner: Option<&'p PyType>) -> Self::Result
where
Self: PyDescrGetProtocol<'p>,
{
unimplemented!()
}
fn __set__(&'p self, instance: &'p PyObjectRef, value: &'p PyObjectRef) -> Self::Result
fn __set__(&'p self, instance: &'p PyAny, value: &'p PyAny) -> Self::Result
where
Self: PyDescrSetProtocol<'p>,
{
unimplemented!()
}
fn __delete__(&'p self, instance: &'p PyObjectRef) -> Self::Result
fn __delete__(&'p self, instance: &'p PyAny) -> Self::Result
where
Self: PyDescrDeleteProtocol<'p>,
{
unimplemented!()
}
fn __set_name__(&'p self, instance: &'p PyObjectRef) -> Self::Result
fn __set_name__(&'p self, instance: &'p PyAny) -> Self::Result
where
Self: PyDescrSetNameProtocol<'p>,
{

View File

@ -87,7 +87,7 @@ macro_rules! py_binary_func {
let _pool = $crate::GILPool::new();
let py = $crate::Python::assume_gil_acquired();
let slf = py.mut_from_borrowed_ptr::<T>(slf);
let arg = py.from_borrowed_ptr::<$crate::types::PyObjectRef>(arg);
let arg = py.from_borrowed_ptr::<$crate::types::PyAny>(arg);
let result = match arg.extract() {
Ok(arg) => slf.$f(arg).into(),
@ -114,8 +114,8 @@ macro_rules! py_binary_num_func {
use $crate::ObjectProtocol;
let _pool = $crate::GILPool::new();
let py = $crate::Python::assume_gil_acquired();
let lhs = py.from_borrowed_ptr::<$crate::types::PyObjectRef>(lhs);
let rhs = py.from_borrowed_ptr::<$crate::types::PyObjectRef>(rhs);
let lhs = py.from_borrowed_ptr::<$crate::types::PyAny>(lhs);
let rhs = py.from_borrowed_ptr::<$crate::types::PyAny>(rhs);
let result = match lhs.extract() {
Ok(lhs) => match rhs.extract() {
@ -147,7 +147,7 @@ macro_rules! py_binary_self_func {
let _pool = $crate::GILPool::new();
let py = $crate::Python::assume_gil_acquired();
let slf1 = py.mut_from_borrowed_ptr::<T>(slf);
let arg = py.from_borrowed_ptr::<$crate::types::PyObjectRef>(arg);
let arg = py.from_borrowed_ptr::<$crate::types::PyAny>(arg);
let result = match arg.extract() {
Ok(arg) => slf1.$f(arg).into(),
@ -216,8 +216,8 @@ macro_rules! py_ternary_func {
let _pool = $crate::GILPool::new();
let py = $crate::Python::assume_gil_acquired();
let slf = py.mut_from_borrowed_ptr::<T>(slf);
let arg1 = py.from_borrowed_ptr::<$crate::types::PyObjectRef>(arg1);
let arg2 = py.from_borrowed_ptr::<$crate::types::PyObjectRef>(arg2);
let arg1 = py.from_borrowed_ptr::<$crate::types::PyAny>(arg1);
let arg2 = py.from_borrowed_ptr::<$crate::types::PyAny>(arg2);
let result = match arg1.extract() {
Ok(arg1) => match arg2.extract() {
@ -249,9 +249,9 @@ macro_rules! py_ternary_num_func {
let _pool = $crate::GILPool::new();
let py = $crate::Python::assume_gil_acquired();
let arg1 = py.from_borrowed_ptr::<$crate::types::PyObjectRef>(arg1);
let arg2 = py.from_borrowed_ptr::<$crate::types::PyObjectRef>(arg2);
let arg3 = py.from_borrowed_ptr::<$crate::types::PyObjectRef>(arg3);
let arg1 = py.from_borrowed_ptr::<$crate::types::PyAny>(arg1);
let arg2 = py.from_borrowed_ptr::<$crate::types::PyAny>(arg2);
let arg3 = py.from_borrowed_ptr::<$crate::types::PyAny>(arg3);
let result = match arg1.extract() {
Ok(arg1) => match arg2.extract() {
@ -287,8 +287,8 @@ macro_rules! py_ternary_self_func {
let _pool = $crate::GILPool::new();
let py = $crate::Python::assume_gil_acquired();
let slf1 = py.mut_from_borrowed_ptr::<T>(slf);
let arg1 = py.from_borrowed_ptr::<$crate::types::PyObjectRef>(arg1);
let arg2 = py.from_borrowed_ptr::<$crate::types::PyObjectRef>(arg2);
let arg1 = py.from_borrowed_ptr::<$crate::types::PyAny>(arg1);
let arg2 = py.from_borrowed_ptr::<$crate::types::PyAny>(arg2);
let result = match arg1.extract() {
Ok(arg1) => match arg2.extract() {
@ -335,8 +335,8 @@ macro_rules! py_func_set {
),
))
} else {
let name = py.mut_from_borrowed_ptr::<$crate::types::PyObjectRef>(name);
let value = py.from_borrowed_ptr::<$crate::types::PyObjectRef>(value);
let name = py.mut_from_borrowed_ptr::<$crate::types::PyAny>(name);
let value = py.from_borrowed_ptr::<$crate::types::PyAny>(value);
match name.extract() {
Ok(name) => match value.extract() {
Ok(value) => slf.$fn_set(name, value).into(),
@ -376,7 +376,7 @@ macro_rules! py_func_del {
let result = if value.is_null() {
let slf = py.mut_from_borrowed_ptr::<U>(slf);
let name = py.from_borrowed_ptr::<$crate::types::PyObjectRef>(name);
let name = py.from_borrowed_ptr::<$crate::types::PyAny>(name);
match name.extract() {
Ok(name) => slf.$fn_del(name).into(),
@ -416,7 +416,7 @@ macro_rules! py_func_set_del {
let _pool = $crate::GILPool::new();
let py = $crate::Python::assume_gil_acquired();
let slf = py.mut_from_borrowed_ptr::<$generic>(slf);
let name = py.from_borrowed_ptr::<$crate::types::PyObjectRef>(name);
let name = py.from_borrowed_ptr::<$crate::types::PyAny>(name);
let result = if value.is_null() {
match name.extract() {
@ -424,7 +424,7 @@ macro_rules! py_func_set_del {
Err(e) => Err(e.into()),
}
} else {
let value = py.from_borrowed_ptr::<$crate::types::PyObjectRef>(value);
let value = py.from_borrowed_ptr::<$crate::types::PyAny>(value);
match name.extract() {
Ok(name) => match value.extract() {
Ok(value) => slf.$fn_set(name, value).into(),

View File

@ -9,7 +9,7 @@ use crate::exceptions;
use crate::ffi;
use crate::objectprotocol::ObjectProtocol;
use crate::type_object::PyTypeInfo;
use crate::types::PyObjectRef;
use crate::types::PyAny;
use crate::Python;
use crate::{FromPyObject, IntoPyObject};
use std::os::raw::c_int;
@ -241,7 +241,7 @@ where
stringify!(T)
)))
} else {
let value = py.from_borrowed_ptr::<PyObjectRef>(value);
let value = py.from_borrowed_ptr::<PyAny>(value);
match value.extract() {
Ok(value) => slf.__setitem__(key as isize, value).into(),
Err(e) => Err(e),
@ -358,7 +358,7 @@ mod sq_ass_item_impl {
let result = if value.is_null() {
slf.__delitem__(key as isize).into()
} else {
let value = py.from_borrowed_ptr::<PyObjectRef>(value);
let value = py.from_borrowed_ptr::<PyAny>(value);
match value.extract() {
Ok(value) => slf.__setitem__(key as isize, value).into(),
Err(e) => Err(e),

View File

@ -6,7 +6,7 @@ use crate::err::{PyDowncastError, PyResult};
use crate::ffi;
use crate::object::PyObject;
use crate::type_object::PyTypeInfo;
use crate::types::PyObjectRef;
use crate::types::PyAny;
use crate::types::PyTuple;
use crate::Py;
use crate::Python;
@ -182,7 +182,7 @@ pub trait IntoPyObject {
/// the inherent method `PyObject::extract()` can be used.
pub trait FromPyObject<'source>: Sized {
/// Extracts `Self` from the source `PyObject`.
fn extract(ob: &'source PyObjectRef) -> PyResult<Self>;
fn extract(ob: &'source PyAny) -> PyResult<Self>;
}
/// Identity conversion: allows using existing `PyObject` instances where
@ -262,7 +262,7 @@ where
T: PyTryFrom<'a>,
{
#[inline]
default fn extract(ob: &'a PyObjectRef) -> PyResult<&'a T> {
default fn extract(ob: &'a PyAny) -> PyResult<&'a T> {
Ok(T::try_from(ob)?)
}
}
@ -273,7 +273,7 @@ where
T: PyTryFrom<'a>,
{
#[inline]
default fn extract(ob: &'a PyObjectRef) -> PyResult<&'a mut T> {
default fn extract(ob: &'a PyAny) -> PyResult<&'a mut T> {
Ok(T::try_from_mut(ob)?)
}
}
@ -282,7 +282,7 @@ impl<'a, T> FromPyObject<'a> for Option<T>
where
T: FromPyObject<'a>,
{
fn extract(obj: &'a PyObjectRef) -> PyResult<Self> {
fn extract(obj: &'a PyAny) -> PyResult<Self> {
if obj.as_ptr() == unsafe { ffi::Py_None() } {
Ok(None)
} else {
@ -314,31 +314,29 @@ pub trait PyTryInto<T>: Sized {
/// This trait is similar to `std::convert::TryFrom`
pub trait PyTryFrom<'v>: Sized {
/// Cast from a concrete Python object type to PyObject.
fn try_from<V: Into<&'v PyObjectRef>>(value: V) -> Result<&'v Self, PyDowncastError>;
fn try_from<V: Into<&'v PyAny>>(value: V) -> Result<&'v Self, PyDowncastError>;
/// Cast from a concrete Python object type to PyObject. With exact type check.
fn try_from_exact<V: Into<&'v PyObjectRef>>(value: V) -> Result<&'v Self, PyDowncastError>;
fn try_from_exact<V: Into<&'v PyAny>>(value: V) -> Result<&'v Self, PyDowncastError>;
/// Cast from a concrete Python object type to PyObject.
fn try_from_mut<V: Into<&'v PyObjectRef>>(value: V) -> Result<&'v mut Self, PyDowncastError>;
fn try_from_mut<V: Into<&'v PyAny>>(value: V) -> Result<&'v mut Self, PyDowncastError>;
/// Cast from a concrete Python object type to PyObject. With exact type check.
fn try_from_mut_exact<V: Into<&'v PyObjectRef>>(
value: V,
) -> Result<&'v mut Self, PyDowncastError>;
fn try_from_mut_exact<V: Into<&'v PyAny>>(value: V) -> Result<&'v mut Self, PyDowncastError>;
/// Cast a PyObjectRef to a specific type of PyObject. The caller must
/// Cast a PyAny to a specific type of PyObject. The caller must
/// have already verified the reference is for this type.
unsafe fn try_from_unchecked<V: Into<&'v PyObjectRef>>(value: V) -> &'v Self;
unsafe fn try_from_unchecked<V: Into<&'v PyAny>>(value: V) -> &'v Self;
/// Cast a PyObjectRef to a specific type of PyObject. The caller must
/// Cast a PyAny to a specific type of PyObject. The caller must
/// have already verified the reference is for this type.
#[allow(clippy::mut_from_ref)]
unsafe fn try_from_mut_unchecked<V: Into<&'v PyObjectRef>>(value: V) -> &'v mut Self;
unsafe fn try_from_mut_unchecked<V: Into<&'v PyAny>>(value: V) -> &'v mut Self;
}
// TryFrom implies TryInto
impl<U> PyTryInto<U> for PyObjectRef
impl<U> PyTryInto<U> for PyAny
where
U: for<'v> PyTryFrom<'v>,
{
@ -360,7 +358,7 @@ impl<'v, T> PyTryFrom<'v> for T
where
T: PyTypeInfo,
{
fn try_from<V: Into<&'v PyObjectRef>>(value: V) -> Result<&'v T, PyDowncastError> {
fn try_from<V: Into<&'v PyAny>>(value: V) -> Result<&'v T, PyDowncastError> {
let value = value.into();
unsafe {
if T::is_instance(value) {
@ -371,7 +369,7 @@ where
}
}
fn try_from_exact<V: Into<&'v PyObjectRef>>(value: V) -> Result<&'v T, PyDowncastError> {
fn try_from_exact<V: Into<&'v PyAny>>(value: V) -> Result<&'v T, PyDowncastError> {
let value = value.into();
unsafe {
if T::is_exact_instance(value) {
@ -382,7 +380,7 @@ where
}
}
fn try_from_mut<V: Into<&'v PyObjectRef>>(value: V) -> Result<&'v mut T, PyDowncastError> {
fn try_from_mut<V: Into<&'v PyAny>>(value: V) -> Result<&'v mut T, PyDowncastError> {
let value = value.into();
unsafe {
if T::is_instance(value) {
@ -393,9 +391,7 @@ where
}
}
fn try_from_mut_exact<V: Into<&'v PyObjectRef>>(
value: V,
) -> Result<&'v mut T, PyDowncastError> {
fn try_from_mut_exact<V: Into<&'v PyAny>>(value: V) -> Result<&'v mut T, PyDowncastError> {
let value = value.into();
unsafe {
if T::is_exact_instance(value) {
@ -407,7 +403,7 @@ where
}
#[inline]
unsafe fn try_from_unchecked<V: Into<&'v PyObjectRef>>(value: V) -> &'v T {
unsafe fn try_from_unchecked<V: Into<&'v PyAny>>(value: V) -> &'v T {
let value = value.into();
let ptr = if T::OFFSET == 0 {
value as *const _ as *const u8 as *const T
@ -418,7 +414,7 @@ where
}
#[inline]
unsafe fn try_from_mut_unchecked<V: Into<&'v PyObjectRef>>(value: V) -> &'v mut T {
unsafe fn try_from_mut_unchecked<V: Into<&'v PyAny>>(value: V) -> &'v mut T {
let value = value.into();
let ptr = if T::OFFSET == 0 {
value as *const _ as *mut u8 as *mut T

View File

@ -8,7 +8,7 @@ use crate::err::PyResult;
use crate::exceptions::TypeError;
use crate::ffi;
use crate::init_once;
use crate::types::{PyDict, PyModule, PyObjectRef, PyString, PyTuple};
use crate::types::{PyAny, PyDict, PyModule, PyString, PyTuple};
use crate::GILPool;
use crate::Python;
use crate::{IntoPyObject, PyTryFrom};
@ -40,7 +40,7 @@ pub fn parse_fn_args<'p>(
kwargs: Option<&'p PyDict>,
accept_args: bool,
accept_kwargs: bool,
output: &mut [Option<&'p PyObjectRef>],
output: &mut [Option<&'p PyAny>],
) -> PyResult<()> {
let nargs = args.len();
let nkeywords = kwargs.map_or(0, PyDict::len);

View File

@ -5,7 +5,7 @@ use crate::ffi;
use crate::instance::Py;
use crate::object::PyObject;
use crate::type_object::PyTypeObject;
use crate::types::{PyObjectRef, PyType};
use crate::types::{PyAny, PyType};
use crate::AsPyPointer;
use crate::IntoPyPointer;
use crate::Python;
@ -115,7 +115,7 @@ impl PyErr {
/// If `obj` is a Python exception type object, the PyErr will (lazily) create a new
/// instance of that type.
/// Otherwise, a `TypeError` is created instead.
pub fn from_instance(obj: &PyObjectRef) -> PyErr {
pub fn from_instance(obj: &PyAny) -> PyErr {
let ptr = obj.as_ptr();
if unsafe { ffi::PyExceptionInstance_Check(ptr) } != 0 {
@ -317,12 +317,7 @@ impl PyErr {
/// Issue a warning message.
/// May return a PyErr if warnings-as-errors is enabled.
pub fn warn(
py: Python,
category: &PyObjectRef,
message: &str,
stacklevel: i32,
) -> PyResult<()> {
pub fn warn(py: Python, category: &PyAny, message: &str, stacklevel: i32) -> PyResult<()> {
let message = CString::new(message)?;
unsafe {
error_on_minusone(

View File

@ -5,7 +5,7 @@
use crate::err::{PyErr, PyResult};
use crate::ffi;
use crate::type_object::PyTypeObject;
use crate::types::{PyObjectRef, PyTuple};
use crate::types::{PyAny, PyTuple};
use crate::Python;
use crate::{AsPyPointer, ToPyObject};
use std::ffi::CStr;
@ -317,7 +317,7 @@ impl UnicodeDecodeError {
input: &[u8],
range: ops::Range<usize>,
reason: &CStr,
) -> PyResult<&'p PyObjectRef> {
) -> PyResult<&'p PyAny> {
unsafe {
let input: &[c_char] = &*(input as *const [u8] as *const [c_char]);
py.from_owned_ptr_or_err(ffi::PyUnicodeDecodeError_Create(
@ -336,7 +336,7 @@ impl UnicodeDecodeError {
py: Python<'p>,
input: &[u8],
err: std::str::Utf8Error,
) -> PyResult<&'p PyObjectRef> {
) -> PyResult<&'p PyAny> {
let pos = err.valid_up_to();
UnicodeDecodeError::new_err(
py,

View File

@ -3,7 +3,7 @@
//! Interaction with python's global interpreter lock
use crate::ffi;
use crate::types::PyObjectRef;
use crate::types::PyAny;
use crate::Python;
use spin;
use std::ptr::NonNull;
@ -230,14 +230,14 @@ pub unsafe fn register_pointer(obj: NonNull<ffi::PyObject>) {
(**pool.p.lock()).push(obj);
}
pub unsafe fn register_owned(_py: Python, obj: NonNull<ffi::PyObject>) -> &PyObjectRef {
pub unsafe fn register_owned(_py: Python, obj: NonNull<ffi::PyObject>) -> &PyAny {
let pool = &mut *POOL;
&*(pool.owned.push_back(obj) as *const _ as *const PyObjectRef)
&*(pool.owned.push_back(obj) as *const _ as *const PyAny)
}
pub unsafe fn register_borrowed(_py: Python, obj: NonNull<ffi::PyObject>) -> &PyObjectRef {
pub unsafe fn register_borrowed(_py: Python, obj: NonNull<ffi::PyObject>) -> &PyAny {
let pool = &mut *POOL;
&*(pool.borrowed.push_back(obj) as *const _ as *const PyObjectRef)
&*(pool.borrowed.push_back(obj) as *const _ as *const PyAny)
}
impl GILGuard {

View File

@ -7,7 +7,7 @@ use crate::object::PyObject;
use crate::objectprotocol::ObjectProtocol;
use crate::type_object::PyTypeCreate;
use crate::type_object::{PyTypeInfo, PyTypeObject};
use crate::types::PyObjectRef;
use crate::types::PyAny;
use crate::AsPyPointer;
use crate::IntoPyPointer;
use crate::Python;
@ -173,24 +173,6 @@ impl<'a, T: PyTypeInfo> DerefMut for PyRefMut<'a, T> {
}
}
impl<'a, T> From<PyRef<'a, T>> for &'a PyObjectRef
where
T: PyTypeInfo,
{
fn from(pref: PyRef<'a, T>) -> &'a PyObjectRef {
unsafe { &*(pref.as_ptr() as *const PyObjectRef) }
}
}
impl<'a, T> From<PyRefMut<'a, T>> for &'a PyObjectRef
where
T: PyTypeInfo,
{
fn from(pref: PyRefMut<'a, T>) -> &'a PyObjectRef {
unsafe { &*(pref.as_ptr() as *const PyObjectRef) }
}
}
/// Trait implements object reference extraction from python managed pointer.
pub trait AsPyRef<T: PyTypeInfo>: Sized {
/// Return reference to object.
@ -484,7 +466,7 @@ where
&'a T: 'a + FromPyObject<'a>,
{
/// Extracts `Self` from the source `PyObject`.
fn extract(ob: &'a PyObjectRef) -> PyResult<Self> {
fn extract(ob: &'a PyAny) -> PyResult<Self> {
unsafe {
ob.extract::<&T>()
.map(|val| Py::from_borrowed_ptr(val.as_ptr()))
@ -506,9 +488,9 @@ where
/// ```
/// use pyo3::ffi;
/// use pyo3::{ToPyObject, AsPyPointer, PyNativeType, ManagedPyRef};
/// use pyo3::types::{PyDict, PyObjectRef};
/// use pyo3::types::{PyDict, PyAny};
///
/// pub fn get_dict_item<'p>(dict: &'p PyDict, key: &impl ToPyObject) -> Option<&'p PyObjectRef> {
/// pub fn get_dict_item<'p>(dict: &'p PyDict, key: &impl ToPyObject) -> Option<&'p PyAny> {
/// let key = ManagedPyRef::from_to_pyobject(dict.py(), key);
/// unsafe {
/// dict.py().from_borrowed_ptr_or_opt(ffi::PyDict_GetItem(dict.as_ptr(), key.as_ptr()))
@ -536,7 +518,7 @@ impl<'p, T: ToPyObject> AsPyPointer for ManagedPyRef<'p, T> {
}
}
/// Helper trait to choose the right implementation for [BorrowedPyRef]
/// Helper trait to choose the right implementation for [ManagedPyRef]
pub trait ManagedPyRefDispatch: ToPyObject {
/// Optionally converts into a python object and stores the pointer to the python heap.
///

View File

@ -4,7 +4,7 @@ use crate::err::{PyDowncastError, PyErr, PyResult};
use crate::ffi;
use crate::gil;
use crate::instance::{AsPyRef, PyNativeType, PyRef, PyRefMut};
use crate::types::{PyDict, PyObjectRef, PyTuple};
use crate::types::{PyAny, PyDict, PyTuple};
use crate::AsPyPointer;
use crate::Py;
use crate::Python;
@ -254,14 +254,14 @@ impl PyObject {
}
}
impl AsPyRef<PyObjectRef> for PyObject {
impl AsPyRef<PyAny> for PyObject {
#[inline]
fn as_ref(&self, _py: Python) -> PyRef<PyObjectRef> {
unsafe { PyRef::from_ref(&*(self as *const _ as *const PyObjectRef)) }
fn as_ref(&self, _py: Python) -> PyRef<PyAny> {
unsafe { PyRef::from_ref(&*(self as *const _ as *const PyAny)) }
}
#[inline]
fn as_mut(&mut self, _py: Python) -> PyRefMut<PyObjectRef> {
unsafe { PyRefMut::from_mut(&mut *(self as *mut _ as *mut PyObjectRef)) }
fn as_mut(&mut self, _py: Python) -> PyRefMut<PyAny> {
unsafe { PyRefMut::from_mut(&mut *(self as *mut _ as *mut PyAny)) }
}
}
@ -309,7 +309,7 @@ impl IntoPyObject for PyObject {
impl<'a> FromPyObject<'a> for PyObject {
#[inline]
/// Extracts `Self` from the source `PyObject`.
fn extract(ob: &'a PyObjectRef) -> PyResult<Self> {
fn extract(ob: &'a PyAny) -> PyResult<Self> {
unsafe { Ok(PyObject::from_borrowed_ptr(ob.py(), ob.as_ptr())) }
}
}

View File

@ -7,7 +7,7 @@ use crate::ffi;
use crate::instance::PyNativeType;
use crate::object::PyObject;
use crate::type_object::PyTypeInfo;
use crate::types::{PyDict, PyIterator, PyObjectRef, PyString, PyTuple, PyType};
use crate::types::{PyAny, PyDict, PyIterator, PyString, PyTuple, PyType};
use crate::AsPyPointer;
use crate::IntoPyPointer;
use crate::Py;
@ -26,7 +26,7 @@ pub trait ObjectProtocol {
/// Retrieves an attribute value.
/// This is equivalent to the Python expression `self.attr_name`.
fn getattr<N>(&self, attr_name: N) -> PyResult<&PyObjectRef>
fn getattr<N>(&self, attr_name: N) -> PyResult<&PyAny>
where
N: ToPyObject;
@ -88,19 +88,15 @@ pub trait ObjectProtocol {
/// Calls the object.
/// This is equivalent to the Python expression: `self(*args, **kwargs)`
fn call(
&self,
args: impl IntoPy<Py<PyTuple>>,
kwargs: Option<&PyDict>,
) -> PyResult<&PyObjectRef>;
fn call(&self, args: impl IntoPy<Py<PyTuple>>, kwargs: Option<&PyDict>) -> PyResult<&PyAny>;
/// Calls the object.
/// This is equivalent to the Python expression: `self()`
fn call0(&self) -> PyResult<&PyObjectRef>;
fn call0(&self) -> PyResult<&PyAny>;
/// Calls the object.
/// This is equivalent to the Python expression: `self(*args)`
fn call1(&self, args: impl IntoPy<Py<PyTuple>>) -> PyResult<&PyObjectRef>;
fn call1(&self, args: impl IntoPy<Py<PyTuple>>) -> PyResult<&PyAny>;
/// Calls a method on the object.
/// This is equivalent to the Python expression: `self.name(*args, **kwargs)`
@ -122,15 +118,15 @@ pub trait ObjectProtocol {
name: &str,
args: impl IntoPy<Py<PyTuple>>,
kwargs: Option<&PyDict>,
) -> PyResult<&PyObjectRef>;
) -> PyResult<&PyAny>;
/// Calls a method on the object.
/// This is equivalent to the Python expression: `self.name()`
fn call_method0(&self, name: &str) -> PyResult<&PyObjectRef>;
fn call_method0(&self, name: &str) -> PyResult<&PyAny>;
/// Calls a method on the object with positional arguments only .
/// This is equivalent to the Python expression: `self.name(*args)`
fn call_method1(&self, name: &str, args: impl IntoPy<Py<PyTuple>>) -> PyResult<&PyObjectRef>;
fn call_method1(&self, name: &str, args: impl IntoPy<Py<PyTuple>>) -> PyResult<&PyAny>;
/// Retrieves the hash code of the object.
/// This is equivalent to the Python expression: `hash(self)`
@ -149,7 +145,7 @@ pub trait ObjectProtocol {
fn len(&self) -> PyResult<usize>;
/// This is equivalent to the Python expression: `self[key]`
fn get_item<K>(&self, key: K) -> PyResult<&PyObjectRef>
fn get_item<K>(&self, key: K) -> PyResult<&PyAny>
where
K: ToBorrowedObject;
@ -192,14 +188,14 @@ pub trait ObjectProtocol {
fn cast_as<'a, D>(&'a self) -> Result<&'a D, PyDowncastError>
where
D: PyTryFrom<'a>,
&'a PyObjectRef: std::convert::From<&'a Self>;
&'a PyAny: std::convert::From<&'a Self>;
/// Extracts some type from the Python object.
/// This is a wrapper function around `FromPyObject::extract()`.
fn extract<'a, D>(&'a self) -> PyResult<D>
where
D: FromPyObject<'a>,
&'a PyObjectRef: std::convert::From<&'a Self>;
&'a PyAny: std::convert::From<&'a Self>;
/// Returns reference count for python object.
fn get_refcnt(&self) -> isize;
@ -222,7 +218,7 @@ where
})
}
fn getattr<N>(&self, attr_name: N) -> PyResult<&PyObjectRef>
fn getattr<N>(&self, attr_name: N) -> PyResult<&PyAny>
where
N: ToPyObject,
{
@ -325,11 +321,7 @@ where
unsafe { ffi::PyCallable_Check(self.as_ptr()) != 0 }
}
fn call(
&self,
args: impl IntoPy<Py<PyTuple>>,
kwargs: Option<&PyDict>,
) -> PyResult<&PyObjectRef> {
fn call(&self, args: impl IntoPy<Py<PyTuple>>, kwargs: Option<&PyDict>) -> PyResult<&PyAny> {
let args = args.into_py(self.py()).into_ptr();
let kwargs = kwargs.into_ptr();
let result = unsafe {
@ -343,11 +335,11 @@ where
result
}
fn call0(&self) -> PyResult<&PyObjectRef> {
fn call0(&self) -> PyResult<&PyAny> {
self.call((), None)
}
fn call1(&self, args: impl IntoPy<Py<PyTuple>>) -> PyResult<&PyObjectRef> {
fn call1(&self, args: impl IntoPy<Py<PyTuple>>) -> PyResult<&PyAny> {
self.call(args, None)
}
@ -356,7 +348,7 @@ where
name: &str,
args: impl IntoPy<Py<PyTuple>>,
kwargs: Option<&PyDict>,
) -> PyResult<&PyObjectRef> {
) -> PyResult<&PyAny> {
name.with_borrowed_ptr(self.py(), |name| unsafe {
let py = self.py();
let ptr = ffi::PyObject_GetAttr(self.as_ptr(), name);
@ -374,11 +366,11 @@ where
})
}
fn call_method0(&self, name: &str) -> PyResult<&PyObjectRef> {
fn call_method0(&self, name: &str) -> PyResult<&PyAny> {
self.call_method(name, (), None)
}
fn call_method1(&self, name: &str, args: impl IntoPy<Py<PyTuple>>) -> PyResult<&PyObjectRef> {
fn call_method1(&self, name: &str, args: impl IntoPy<Py<PyTuple>>) -> PyResult<&PyAny> {
self.call_method(name, args, None)
}
@ -413,7 +405,7 @@ where
}
}
fn get_item<K>(&self, key: K) -> PyResult<&PyObjectRef>
fn get_item<K>(&self, key: K) -> PyResult<&PyAny>
where
K: ToBorrowedObject,
{
@ -474,7 +466,7 @@ where
fn cast_as<'a, D>(&'a self) -> Result<&'a D, PyDowncastError>
where
D: PyTryFrom<'a>,
&'a PyObjectRef: std::convert::From<&'a Self>,
&'a PyAny: std::convert::From<&'a Self>,
{
D::try_from(self)
}
@ -482,7 +474,7 @@ where
fn extract<'a, D>(&'a self) -> PyResult<D>
where
D: FromPyObject<'a>,
&'a PyObjectRef: std::convert::From<&'a T>,
&'a PyAny: std::convert::From<&'a T>,
{
FromPyObject::extract(self.into())
}

View File

@ -8,7 +8,7 @@ use crate::gil::{self, GILGuard};
use crate::instance::AsPyRef;
use crate::object::PyObject;
use crate::type_object::{PyTypeInfo, PyTypeObject};
use crate::types::{PyDict, PyModule, PyObjectRef, PyType};
use crate::types::{PyAny, PyDict, PyModule, PyType};
use crate::AsPyPointer;
use crate::{IntoPyPointer, PyTryFrom};
use std::ffi::CString;
@ -95,7 +95,7 @@ impl<'p> Python<'p> {
code: &str,
globals: Option<&PyDict>,
locals: Option<&PyDict>,
) -> PyResult<&'p PyObjectRef> {
) -> PyResult<&'p PyAny> {
self.run_code(code, ffi::Py_eval_input, globals, locals)
}
@ -108,7 +108,7 @@ impl<'p> Python<'p> {
code: &str,
globals: Option<&PyDict>,
locals: Option<&PyDict>,
) -> PyResult<&'p PyObjectRef> {
) -> PyResult<&'p PyAny> {
self.run_code(code, ffi::Py_file_input, globals, locals)
}
@ -124,7 +124,7 @@ impl<'p> Python<'p> {
start: c_int,
globals: Option<&PyDict>,
locals: Option<&PyDict>,
) -> PyResult<&'p PyObjectRef> {
) -> PyResult<&'p PyAny> {
let code = CString::new(code)?;
unsafe {
@ -193,7 +193,7 @@ impl<'p> Python<'p> {
}
impl<'p> Python<'p> {
unsafe fn unchecked_downcast<T: PyTypeInfo>(self, ob: &PyObjectRef) -> &'p T {
unsafe fn unchecked_downcast<T: PyTypeInfo>(self, ob: &PyAny) -> &'p T {
if T::OFFSET == 0 {
&*(ob as *const _ as *const T)
} else {
@ -203,7 +203,7 @@ impl<'p> Python<'p> {
}
#[allow(clippy::cast_ref_to_mut)] // FIXME
unsafe fn unchecked_mut_downcast<T: PyTypeInfo>(self, ob: &PyObjectRef) -> &'p mut T {
unsafe fn unchecked_mut_downcast<T: PyTypeInfo>(self, ob: &PyAny) -> &'p mut T {
if T::OFFSET == 0 {
&mut *(ob as *const _ as *mut T)
} else {
@ -231,7 +231,7 @@ impl<'p> Python<'p> {
}
/// Register `ffi::PyObject` pointer in release pool
pub unsafe fn from_borrowed_ptr_to_obj(self, ptr: *mut ffi::PyObject) -> &'p PyObjectRef {
pub unsafe fn from_borrowed_ptr_to_obj(self, ptr: *mut ffi::PyObject) -> &'p PyAny {
match NonNull::new(ptr) {
Some(p) => gil::register_borrowed(self, p),
None => crate::err::panic_after_error(),
@ -390,7 +390,7 @@ impl<'p> Python<'p> {
#[cfg(test)]
mod test {
use crate::objectprotocol::ObjectProtocol;
use crate::types::{PyBool, PyDict, PyInt, PyList, PyObjectRef};
use crate::types::{PyAny, PyBool, PyDict, PyInt, PyList};
use crate::Python;
#[test]
@ -440,7 +440,7 @@ mod test {
let gil = Python::acquire_gil();
let py = gil.python();
assert!(py
.is_instance::<PyBool, PyObjectRef>(PyBool::new(py, true).into())
.is_instance::<PyBool, PyAny>(PyBool::new(py, true).into())
.unwrap());
let list = PyList::new(py, &[1, 2, 3, 4]);
assert!(!py.is_instance::<PyBool, _>(list.as_ref()).unwrap());

View File

@ -5,7 +5,7 @@
use crate::class::methods::PyMethodDefType;
use crate::err::{PyErr, PyResult};
use crate::instance::{Py, PyNativeType};
use crate::types::PyObjectRef;
use crate::types::PyAny;
use crate::types::PyType;
use crate::AsPyPointer;
use crate::IntoPyPointer;
@ -45,12 +45,12 @@ pub trait PyTypeInfo {
unsafe fn type_object() -> &'static mut ffi::PyTypeObject;
/// Check if `*mut ffi::PyObject` is instance of this type
fn is_instance(object: &PyObjectRef) -> bool {
fn is_instance(object: &PyAny) -> bool {
unsafe { ffi::PyObject_TypeCheck(object.as_ptr(), Self::type_object()) != 0 }
}
/// Check if `*mut ffi::PyObject` is exact instance of this type
fn is_exact_instance(object: &PyObjectRef) -> bool {
fn is_exact_instance(object: &PyAny) -> bool {
unsafe { (*object.as_ptr()).ob_type == Self::type_object() }
}
}

60
src/types/any.rs Normal file
View File

@ -0,0 +1,60 @@
use crate::conversion::AsPyPointer;
use crate::err::PyDowncastError;
use crate::{ffi, PyObject, PyRef, PyRefMut, PyTryFrom, PyTypeInfo};
/// Represents a python's [Any](https://docs.python.org/3/library/typing.html#typing.Any) type.
/// We can convert all python objects as `PyAny`.
///
/// In addition, if the inner object is an instance of type `T`, we can downcast
/// `PyAny` into `T`.
///
/// # Example
///
/// ```
/// use pyo3::prelude::*;
/// use pyo3::types::{PyAny, PyDict, PyList};
/// let gil = Python::acquire_gil();
/// let dict = PyDict::new(gil.python());
/// assert!(gil.python().is_instance::<PyAny, _>(dict).unwrap());
/// let any = dict.as_ref();
/// assert!(any.downcast_ref::<PyDict>().is_ok());
/// assert!(any.downcast_ref::<PyList>().is_err());
/// ```
#[repr(transparent)]
pub struct PyAny(PyObject);
pyobject_native_type_named!(PyAny);
pyobject_native_type_convert!(PyAny, ffi::PyBaseObject_Type, ffi::PyObject_Check);
impl PyAny {
pub fn downcast_ref<T>(&self) -> Result<&T, PyDowncastError>
where
T: for<'gil> PyTryFrom<'gil>,
{
T::try_from(self)
}
pub fn downcast_mut<T>(&self) -> Result<&mut T, PyDowncastError>
where
T: for<'gil> PyTryFrom<'gil>,
{
T::try_from_mut(self)
}
}
impl<'a, T> From<PyRef<'a, T>> for &'a PyAny
where
T: PyTypeInfo,
{
fn from(pref: PyRef<'a, T>) -> &'a PyAny {
unsafe { &*(pref.as_ptr() as *const PyAny) }
}
}
impl<'a, T> From<PyRefMut<'a, T>> for &'a PyAny
where
T: PyTypeInfo,
{
fn from(pref: PyRefMut<'a, T>) -> &'a PyAny {
unsafe { &*(pref.as_ptr() as *const PyAny) }
}
}

View File

@ -1,7 +1,7 @@
// Copyright (c) 2017-present PyO3 Project and Contributors
use crate::ffi;
use crate::object::PyObject;
use crate::types::PyObjectRef;
use crate::types::PyAny;
use crate::AsPyPointer;
use crate::FromPyObject;
use crate::PyResult;
@ -56,7 +56,7 @@ impl IntoPyObject for bool {
///
/// Fails with `TypeError` if the input is not a Python `bool`.
impl<'source> FromPyObject<'source> for bool {
fn extract(obj: &'source PyObjectRef) -> PyResult<Self> {
fn extract(obj: &'source PyAny) -> PyResult<Self> {
Ok(<PyBool as PyTryFrom>::try_from(obj)?.is_true())
}
}
@ -64,7 +64,7 @@ impl<'source> FromPyObject<'source> for bool {
#[cfg(test)]
mod test {
use crate::objectprotocol::ObjectProtocol;
use crate::types::{PyBool, PyObjectRef};
use crate::types::{PyAny, PyBool};
use crate::Python;
use crate::ToPyObject;
@ -73,7 +73,7 @@ mod test {
let gil = Python::acquire_gil();
let py = gil.python();
assert!(PyBool::new(py, true).is_true());
let t: &PyObjectRef = PyBool::new(py, true).into();
let t: &PyAny = PyBool::new(py, true).into();
assert_eq!(true, t.extract().unwrap());
assert_eq!(true.to_object(py), PyBool::new(py, true).into());
}
@ -83,7 +83,7 @@ mod test {
let gil = Python::acquire_gil();
let py = gil.python();
assert!(!PyBool::new(py, false).is_true());
let t: &PyObjectRef = PyBool::new(py, false).into();
let t: &PyAny = PyBool::new(py, false).into();
assert_eq!(false, t.extract().unwrap());
assert_eq!(false.to_object(py), PyBool::new(py, false).into());
}

View File

@ -119,7 +119,7 @@ impl<'py> Neg for &'py PyComplex {
mod complex_conversion {
use super::*;
use crate::err::PyErr;
use crate::types::PyObjectRef;
use crate::types::PyAny;
use crate::PyResult;
use crate::{FromPyObject, IntoPyObject, ToPyObject};
use num_complex::Complex;
@ -156,7 +156,7 @@ mod complex_conversion {
#[cfg(any(not(Py_LIMITED_API), not(Py_3)))]
#[allow(clippy::float_cmp)] // The comparison is for an error value
impl<'source> FromPyObject<'source> for Complex<$float> {
fn extract(obj: &'source PyObjectRef) -> PyResult<Complex<$float>> {
fn extract(obj: &'source PyAny) -> PyResult<Complex<$float>> {
unsafe {
let val = ffi::PyComplex_AsCComplex(obj.as_ptr());
if val.real == -1.0 && PyErr::occurred(obj.py()) {
@ -170,7 +170,7 @@ mod complex_conversion {
#[cfg(all(Py_LIMITED_API, Py_3))]
#[allow(clippy::float_cmp)] // The comparison is for an error value
impl<'source> FromPyObject<'source> for Complex<$float> {
fn extract(obj: &'source PyObjectRef) -> PyResult<Complex<$float>> {
fn extract(obj: &'source PyAny) -> PyResult<Complex<$float>> {
unsafe {
let ptr = obj.as_ptr();
let real = ffi::PyComplex_RealAsDouble(ptr);

View File

@ -4,7 +4,7 @@ use crate::err::{self, PyErr, PyResult};
use crate::ffi;
use crate::instance::PyNativeType;
use crate::object::PyObject;
use crate::types::{PyList, PyObjectRef};
use crate::types::{PyAny, PyList};
use crate::AsPyPointer;
use crate::IntoPyPointer;
use crate::Python;
@ -83,7 +83,7 @@ impl PyDict {
/// Gets an item from the dictionary.
/// Returns None if the item is not present, or if an error occurs.
pub fn get_item<K>(&self, key: K) -> Option<&PyObjectRef>
pub fn get_item<K>(&self, key: K) -> Option<&PyAny>
where
K: ToBorrowedObject,
{
@ -165,7 +165,7 @@ pub struct PyDictIterator<'py> {
}
impl<'py> Iterator for PyDictIterator<'py> {
type Item = (&'py PyObjectRef, &'py PyObjectRef);
type Item = (&'py PyAny, &'py PyAny);
#[inline]
fn next(&mut self) -> Option<Self::Item> {
@ -183,7 +183,7 @@ impl<'py> Iterator for PyDictIterator<'py> {
}
impl<'a> std::iter::IntoIterator for &'a PyDict {
type Item = (&'a PyObjectRef, &'a PyObjectRef);
type Item = (&'a PyAny, &'a PyAny);
type IntoIter = PyDictIterator<'a>;
fn into_iter(self) -> Self::IntoIter {

View File

@ -7,7 +7,7 @@ use crate::ffi;
use crate::instance::{Py, PyNativeType};
use crate::object::PyObject;
use crate::objectprotocol::ObjectProtocol;
use crate::types::PyObjectRef;
use crate::types::PyAny;
use crate::AsPyPointer;
use crate::FromPyObject;
use crate::PyResult;
@ -53,7 +53,7 @@ impl IntoPyObject for f64 {
impl<'source> FromPyObject<'source> for f64 {
// PyFloat_AsDouble returns -1.0 upon failure
#![cfg_attr(feature = "cargo-clippy", allow(clippy::float_cmp))]
fn extract(obj: &'source PyObjectRef) -> PyResult<Self> {
fn extract(obj: &'source PyAny) -> PyResult<Self> {
let v = unsafe { ffi::PyFloat_AsDouble(obj.as_ptr()) };
if v == -1.0 && PyErr::occurred(obj.py()) {
@ -77,7 +77,7 @@ impl IntoPyObject for f32 {
}
impl<'source> FromPyObject<'source> for f32 {
fn extract(obj: &'source PyObjectRef) -> PyResult<Self> {
fn extract(obj: &'source PyAny) -> PyResult<Self> {
Ok(obj.extract::<f64>()? as f32)
}
}

View File

@ -5,7 +5,7 @@
use crate::err::{PyDowncastError, PyErr, PyResult};
use crate::ffi;
use crate::instance::PyNativeType;
use crate::types::PyObjectRef;
use crate::types::PyAny;
use crate::AsPyPointer;
use crate::Python;
@ -30,7 +30,7 @@ use crate::Python;
/// # Ok(())
/// # }
/// ```
pub struct PyIterator<'p>(&'p PyObjectRef);
pub struct PyIterator<'p>(&'p PyAny);
impl<'p> PyIterator<'p> {
/// Constructs a `PyIterator` from a Python iterator object.
@ -52,7 +52,7 @@ impl<'p> PyIterator<'p> {
}
impl<'p> Iterator for PyIterator<'p> {
type Item = PyResult<&'p PyObjectRef>;
type Item = PyResult<&'p PyAny>;
/// Retrieves the next item from an iterator.
/// Returns `None` when the iterator is exhausted.

View File

@ -6,7 +6,7 @@ use crate::err::{self, PyResult};
use crate::ffi::{self, Py_ssize_t};
use crate::instance::PyNativeType;
use crate::object::PyObject;
use crate::types::PyObjectRef;
use crate::types::PyAny;
use crate::AsPyPointer;
use crate::IntoPyPointer;
use crate::Python;
@ -59,7 +59,7 @@ impl PyList {
/// Gets the item at the specified index.
///
/// Panics if the index is out of range.
pub fn get_item(&self, index: isize) -> &PyObjectRef {
pub fn get_item(&self, index: isize) -> &PyAny {
unsafe {
self.py()
.from_borrowed_ptr(ffi::PyList_GetItem(self.as_ptr(), index as Py_ssize_t))
@ -141,10 +141,10 @@ pub struct PyListIterator<'a> {
}
impl<'a> Iterator for PyListIterator<'a> {
type Item = &'a PyObjectRef;
type Item = &'a PyAny;
#[inline]
fn next(&mut self) -> Option<&'a PyObjectRef> {
fn next(&mut self) -> Option<&'a PyAny> {
if self.index < self.list.len() as isize {
let item = self.list.get_item(self.index);
self.index += 1;
@ -156,7 +156,7 @@ impl<'a> Iterator for PyListIterator<'a> {
}
impl<'a> std::iter::IntoIterator for &'a PyList {
type Item = &'a PyObjectRef;
type Item = &'a PyAny;
type IntoIter = PyListIterator<'a>;
fn into_iter(self) -> Self::IntoIter {

View File

@ -2,6 +2,7 @@
//! Various types defined by the python interpreter such as `int`, `str` and `tuple`
pub use self::any::PyAny;
pub use self::boolobject::PyBool;
pub use self::bytearray::PyByteArray;
pub use self::complex::PyComplex;
@ -29,8 +30,6 @@ pub use self::string::{PyBytes, PyString, PyString as PyUnicode};
pub use self::string2::{PyBytes, PyString, PyUnicode};
pub use self::tuple::PyTuple;
pub use self::typeobject::PyType;
use crate::ffi;
use crate::PyObject;
/// Implements a typesafe conversions throught [FromPyObject], given a typecheck function as second
/// parameter
@ -40,11 +39,11 @@ macro_rules! pyobject_downcast (
impl<'a, $($type_param,)*> $crate::FromPyObject<'a> for &'a $name
{
/// Extracts `Self` from the source `PyObject`.
fn extract(ob: &'a $crate::types::PyObjectRef) -> $crate::PyResult<Self>
fn extract(ob: &'a $crate::types::PyAny) -> $crate::PyResult<Self>
{
unsafe {
if $checkfunction(ob.as_ptr()) != 0 {
Ok(&*(ob as *const $crate::types::PyObjectRef as *const $name))
Ok(&*(ob as *const $crate::types::PyAny as *const $name))
} else {
Err($crate::PyDowncastError.into())
}
@ -57,10 +56,10 @@ macro_rules! pyobject_downcast (
#[macro_export]
macro_rules! pyobject_native_type_named (
($name: ty $(,$type_param: ident)*) => {
impl<$($type_param,)*> ::std::convert::AsRef<$crate::types::PyObjectRef> for $name {
impl<$($type_param,)*> ::std::convert::AsRef<$crate::types::PyAny> for $name {
#[inline]
fn as_ref(&self) -> &$crate::types::PyObjectRef {
unsafe{&*(self as *const $name as *const $crate::types::PyObjectRef)}
fn as_ref(&self) -> &$crate::types::PyAny {
unsafe{&*(self as *const $name as *const $crate::types::PyAny)}
}
}
@ -91,9 +90,9 @@ macro_rules! pyobject_native_type (
pyobject_native_type_named!($name $(,$type_param)*);
pyobject_native_type_convert!($name, $typeobject, $checkfunction $(,$type_param)*);
impl<'a, $($type_param,)*> ::std::convert::From<&'a $name> for &'a $crate::types::PyObjectRef {
impl<'a, $($type_param,)*> ::std::convert::From<&'a $name> for &'a $crate::types::PyAny {
fn from(ob: &'a $name) -> Self {
unsafe{&*(ob as *const $name as *const $crate::types::PyObjectRef)}
unsafe{&*(ob as *const $name as *const $crate::types::PyAny)}
}
}
};
@ -104,7 +103,7 @@ macro_rules! pyobject_native_type_convert(
($name: ty, $typeobject: expr, $checkfunction: path $(,$type_param: ident)*) => {
impl<$($type_param,)*> $crate::type_object::PyTypeInfo for $name {
type Type = ();
type BaseType = $crate::types::PyObjectRef;
type BaseType = $crate::types::PyAny;
const NAME: &'static str = stringify!($name);
const SIZE: usize = ::std::mem::size_of::<$crate::ffi::PyObject>();
@ -116,7 +115,7 @@ macro_rules! pyobject_native_type_convert(
}
#[allow(unused_unsafe)]
fn is_instance(ptr: &$crate::types::PyObjectRef) -> bool {
fn is_instance(ptr: &$crate::types::PyAny) -> bool {
use $crate::AsPyPointer;
unsafe { $checkfunction(ptr.as_ptr()) > 0 }
@ -138,7 +137,6 @@ macro_rules! pyobject_native_type_convert(
#[inline]
fn to_object(&self, py: $crate::Python) -> $crate::PyObject {
use $crate::AsPyPointer;
unsafe {$crate::PyObject::from_borrowed_ptr(py, self.0.as_ptr())}
}
}
@ -165,12 +163,7 @@ macro_rules! pyobject_native_type_convert(
};
);
/// Represents general python instance.
#[repr(transparent)]
pub struct PyObjectRef(PyObject);
pyobject_native_type_named!(PyObjectRef);
pyobject_native_type_convert!(PyObjectRef, ffi::PyBaseObject_Type, ffi::PyObject_Check);
mod any;
mod boolobject;
mod bytearray;
mod complex;

View File

@ -11,7 +11,7 @@ use crate::objectprotocol::ObjectProtocol;
use crate::type_object::PyTypeCreate;
use crate::type_object::PyTypeObject;
use crate::types::PyTuple;
use crate::types::{PyDict, PyObjectRef};
use crate::types::{PyAny, PyDict};
use crate::AsPyPointer;
use crate::IntoPy;
use crate::Py;
@ -115,25 +115,25 @@ impl PyModule {
name: &str,
args: impl IntoPy<Py<PyTuple>>,
kwargs: Option<&PyDict>,
) -> PyResult<&PyObjectRef> {
) -> PyResult<&PyAny> {
self.getattr(name)?.call(args, kwargs)
}
/// Calls a function in the module.
/// This is equivalent to the Python expression: `getattr(module, name)()`
pub fn call0(&self, name: &str) -> PyResult<&PyObjectRef> {
pub fn call0(&self, name: &str) -> PyResult<&PyAny> {
self.getattr(name)?.call0()
}
/// Calls a function in the module.
/// This is equivalent to the Python expression: `getattr(module, name)(*args)`
pub fn call1(&self, name: &str, args: impl IntoPy<Py<PyTuple>>) -> PyResult<&PyObjectRef> {
pub fn call1(&self, name: &str, args: impl IntoPy<Py<PyTuple>>) -> PyResult<&PyAny> {
self.getattr(name)?.call1(args)
}
/// Gets a member from the module.
/// This is equivalent to the Python expression: `getattr(module, name)`
pub fn get(&self, name: &str) -> PyResult<&PyObjectRef> {
pub fn get(&self, name: &str) -> PyResult<&PyAny> {
self.getattr(name)
}

View File

@ -8,7 +8,7 @@ use crate::exceptions;
use crate::ffi;
use crate::instance::{Py, PyNativeType};
use crate::object::PyObject;
use crate::types::PyObjectRef;
use crate::types::PyAny;
use crate::AsPyPointer;
use crate::IntoPyPointer;
use crate::Python;
@ -79,7 +79,7 @@ macro_rules! int_fits_c_long(
}
impl<'source> FromPyObject<'source> for $rust_type {
fn extract(obj: &'source PyObjectRef) -> PyResult<Self> {
fn extract(obj: &'source PyAny) -> PyResult<Self> {
let val = unsafe { ffi::PyLong_AsLong(obj.as_ptr()) };
if val == -1 && PyErr::occurred(obj.py()) {
return Err(PyErr::fetch(obj.py()));
@ -119,7 +119,7 @@ macro_rules! int_convert_u64_or_i64 (
}
impl <'source> FromPyObject<'source> for $rust_type {
fn extract(obj: &'source PyObjectRef) -> PyResult<$rust_type>
fn extract(obj: &'source PyAny) -> PyResult<$rust_type>
{
let ptr = obj.as_ptr();
unsafe {

View File

@ -8,7 +8,7 @@ use crate::exceptions;
use crate::ffi;
use crate::instance::PyNativeType;
use crate::object::PyObject;
use crate::types::PyObjectRef;
use crate::types::PyAny;
use crate::AsPyPointer;
use crate::Python;
use crate::{FromPyObject, IntoPyObject, ToPyObject};
@ -47,7 +47,7 @@ macro_rules! int_fits_c_long (
}
impl<'source> FromPyObject<'source> for $rust_type {
fn extract(obj: &'source PyObjectRef) -> PyResult<Self> {
fn extract(obj: &'source PyAny) -> PyResult<Self> {
let ptr = obj.as_ptr();
let val = unsafe {
let num = ffi::PyNumber_Index(ptr);
@ -87,7 +87,7 @@ macro_rules! int_convert_u64_or_i64 (
}
}
impl<'source> FromPyObject<'source> for $rust_type {
fn extract(ob: &'source PyObjectRef) -> PyResult<$rust_type>
fn extract(ob: &'source PyAny) -> PyResult<$rust_type>
{
let ptr = ob.as_ptr();
unsafe {

View File

@ -32,7 +32,7 @@ macro_rules! int_fits_larger_int (
}
impl<'source> FromPyObject<'source> for $rust_type {
fn extract(obj: &'source PyObjectRef) -> PyResult<Self> {
fn extract(obj: &'source PyAny) -> PyResult<Self> {
let val = $crate::objectprotocol::ObjectProtocol::extract::<$larger_type>(obj)?;
match cast::<$larger_type, $rust_type>(val) {
Some(v) => Ok(v),
@ -71,7 +71,7 @@ macro_rules! int_convert_bignum (
}
}
impl<'source> FromPyObject<'source> for $rust_type {
fn extract(ob: &'source PyObjectRef) -> PyResult<$rust_type> {
fn extract(ob: &'source PyAny) -> PyResult<$rust_type> {
unsafe {
let num = ffi::PyNumber_Index(ob.as_ptr());
if num.is_null() {

View File

@ -6,7 +6,7 @@ use crate::ffi::{self, Py_ssize_t};
use crate::instance::PyNativeType;
use crate::object::PyObject;
use crate::objectprotocol::ObjectProtocol;
use crate::types::{PyList, PyObjectRef, PyTuple};
use crate::types::{PyAny, PyList, PyTuple};
use crate::AsPyPointer;
use crate::{FromPyObject, PyTryFrom, ToBorrowedObject};
@ -33,11 +33,11 @@ impl PySequence {
unsafe {
let ptr = self
.py()
.from_owned_ptr_or_err::<PyObjectRef>(ffi::PySequence_Concat(
.from_owned_ptr_or_err::<PyAny>(ffi::PySequence_Concat(
self.as_ptr(),
other.as_ptr(),
))?;
Ok(&*(ptr as *const PyObjectRef as *const PySequence))
Ok(&*(ptr as *const PyAny as *const PySequence))
}
}
@ -49,11 +49,11 @@ impl PySequence {
unsafe {
let ptr = self
.py()
.from_owned_ptr_or_err::<PyObjectRef>(ffi::PySequence_Repeat(
.from_owned_ptr_or_err::<PyAny>(ffi::PySequence_Repeat(
self.as_ptr(),
count as Py_ssize_t,
))?;
Ok(&*(ptr as *const PyObjectRef as *const PySequence))
Ok(&*(ptr as *const PyAny as *const PySequence))
}
}
@ -87,7 +87,7 @@ impl PySequence {
/// Return the ith element of the Sequence. Equivalent to python `o[index]`
#[inline]
pub fn get_item(&self, index: isize) -> PyResult<&PyObjectRef> {
pub fn get_item(&self, index: isize) -> PyResult<&PyAny> {
unsafe {
self.py()
.from_owned_ptr_or_err(ffi::PySequence_GetItem(self.as_ptr(), index as Py_ssize_t))
@ -97,7 +97,7 @@ impl PySequence {
/// Return the slice of sequence object o between begin and end.
/// This is the equivalent of the Python expression `o[begin:end]`
#[inline]
pub fn get_slice(&self, begin: isize, end: isize) -> PyResult<&PyObjectRef> {
pub fn get_slice(&self, begin: isize, end: isize) -> PyResult<&PyAny> {
unsafe {
self.py().from_owned_ptr_or_err(ffi::PySequence_GetSlice(
self.as_ptr(),
@ -139,7 +139,7 @@ impl PySequence {
/// Assign the sequence object v to the slice in sequence object o from i1 to i2.
/// This is the equivalent of the Python statement `o[i1:i2] = v`
#[inline]
pub fn set_slice(&self, i1: isize, i2: isize, v: &PyObjectRef) -> PyResult<()> {
pub fn set_slice(&self, i1: isize, i2: isize, v: &PyAny) -> PyResult<()> {
unsafe {
err::error_on_minusone(
self.py(),
@ -238,7 +238,7 @@ impl<'a, T> FromPyObject<'a> for Vec<T>
where
T: FromPyObject<'a>,
{
default fn extract(obj: &'a PyObjectRef) -> PyResult<Self> {
default fn extract(obj: &'a PyAny) -> PyResult<Self> {
extract_sequence(obj)
}
}
@ -247,7 +247,7 @@ impl<'source, T> FromPyObject<'source> for Vec<T>
where
for<'a> T: FromPyObject<'a> + buffer::Element + Copy,
{
fn extract(obj: &'source PyObjectRef) -> PyResult<Self> {
fn extract(obj: &'source PyAny) -> PyResult<Self> {
// first try buffer protocol
if let Ok(buf) = buffer::PyBuffer::get(obj.py(), obj) {
if buf.dimensions() == 1 {
@ -263,7 +263,7 @@ where
}
}
fn extract_sequence<'s, T>(obj: &'s PyObjectRef) -> PyResult<Vec<T>>
fn extract_sequence<'s, T>(obj: &'s PyAny) -> PyResult<Vec<T>>
where
T: FromPyObject<'s>,
{
@ -276,7 +276,7 @@ where
}
impl<'v> PyTryFrom<'v> for PySequence {
fn try_from<V: Into<&'v PyObjectRef>>(value: V) -> Result<&'v PySequence, PyDowncastError> {
fn try_from<V: Into<&'v PyAny>>(value: V) -> Result<&'v PySequence, PyDowncastError> {
let value = value.into();
unsafe {
if ffi::PySequence_Check(value.as_ptr()) != 0 {
@ -287,15 +287,11 @@ impl<'v> PyTryFrom<'v> for PySequence {
}
}
fn try_from_exact<V: Into<&'v PyObjectRef>>(
value: V,
) -> Result<&'v PySequence, PyDowncastError> {
fn try_from_exact<V: Into<&'v PyAny>>(value: V) -> Result<&'v PySequence, PyDowncastError> {
<PySequence as PyTryFrom>::try_from(value)
}
fn try_from_mut<V: Into<&'v PyObjectRef>>(
value: V,
) -> Result<&'v mut PySequence, PyDowncastError> {
fn try_from_mut<V: Into<&'v PyAny>>(value: V) -> Result<&'v mut PySequence, PyDowncastError> {
let value = value.into();
unsafe {
if ffi::PySequence_Check(value.as_ptr()) != 0 {
@ -306,20 +302,20 @@ impl<'v> PyTryFrom<'v> for PySequence {
}
}
fn try_from_mut_exact<V: Into<&'v PyObjectRef>>(
fn try_from_mut_exact<V: Into<&'v PyAny>>(
value: V,
) -> Result<&'v mut PySequence, PyDowncastError> {
<PySequence as PyTryFrom>::try_from_mut(value)
}
#[inline]
unsafe fn try_from_unchecked<V: Into<&'v PyObjectRef>>(value: V) -> &'v PySequence {
unsafe fn try_from_unchecked<V: Into<&'v PyAny>>(value: V) -> &'v PySequence {
let ptr = value.into() as *const _ as *const PySequence;
&*ptr
}
#[inline]
unsafe fn try_from_mut_unchecked<V: Into<&'v PyObjectRef>>(value: V) -> &'v mut PySequence {
unsafe fn try_from_mut_unchecked<V: Into<&'v PyAny>>(value: V) -> &'v mut PySequence {
let ptr = value.into() as *const _ as *mut PySequence;
&mut *ptr
}

View File

@ -5,7 +5,7 @@ use crate::exceptions;
use crate::ffi;
use crate::instance::{Py, PyNativeType};
use crate::object::PyObject;
use crate::types::PyObjectRef;
use crate::types::PyAny;
use crate::AsPyPointer;
use crate::Python;
use std::borrow::Cow;
@ -34,11 +34,7 @@ impl PyString {
unsafe { Py::from_owned_ptr_or_panic(ffi::PyUnicode_FromStringAndSize(ptr, len)) }
}
pub fn from_object<'p>(
src: &'p PyObjectRef,
encoding: &str,
errors: &str,
) -> PyResult<&'p PyString> {
pub fn from_object<'p>(src: &'p PyAny, encoding: &str, errors: &str) -> PyResult<&'p PyString> {
unsafe {
src.py()
.from_owned_ptr_or_err::<PyString>(ffi::PyUnicode_FromEncodedObject(

View File

@ -2,7 +2,7 @@
//
// based on Daniel Grunwald's https://github.com/dgrunwald/rust-cpython
use super::PyObjectRef;
use super::PyAny;
use crate::err::{PyErr, PyResult};
use crate::exceptions;
use crate::ffi;
@ -50,7 +50,7 @@ impl PyString {
}
}
pub fn from_object(src: &PyObjectRef, encoding: &str, errors: &str) -> PyResult<Py<PyString>> {
pub fn from_object(src: &PyAny, encoding: &str, errors: &str) -> PyResult<Py<PyString>> {
unsafe {
Ok(Py::from_owned_ptr_or_err(
src.py(),
@ -137,7 +137,7 @@ impl PyUnicode {
unsafe { Py::from_owned_ptr_or_panic(ffi::PyUnicode_FromStringAndSize(ptr, len)) }
}
pub fn from_object(src: &PyObjectRef, encoding: &str, errors: &str) -> PyResult<Py<PyUnicode>> {
pub fn from_object(src: &PyAny, encoding: &str, errors: &str) -> PyResult<Py<PyUnicode>> {
unsafe {
Ok(Py::from_owned_ptr_or_err(
src.py(),

View File

@ -1,7 +1,7 @@
use crate::err::PyResult;
use crate::instance::PyNativeType;
use crate::object::PyObject;
use crate::types::{PyObjectRef, PyString};
use crate::types::{PyAny, PyString};
use crate::FromPyObject;
use crate::Python;
use crate::{IntoPyObject, PyTryFrom, ToPyObject};
@ -58,7 +58,7 @@ impl<'a> IntoPyObject for &'a String {
/// Allows extracting strings from Python objects.
/// Accepts Python `str` and `unicode` objects.
impl<'source> crate::FromPyObject<'source> for Cow<'source, str> {
fn extract(ob: &'source PyObjectRef) -> PyResult<Self> {
fn extract(ob: &'source PyAny) -> PyResult<Self> {
<PyString as PyTryFrom>::try_from(ob)?.to_string()
}
}
@ -66,7 +66,7 @@ impl<'source> crate::FromPyObject<'source> for Cow<'source, str> {
/// Allows extracting strings from Python objects.
/// Accepts Python `str` and `unicode` objects.
impl<'a> crate::FromPyObject<'a> for &'a str {
fn extract(ob: &'a PyObjectRef) -> PyResult<Self> {
fn extract(ob: &'a PyAny) -> PyResult<Self> {
let s: Cow<'a, str> = crate::FromPyObject::extract(ob)?;
match s {
Cow::Borrowed(r) => Ok(r),
@ -81,7 +81,7 @@ impl<'a> crate::FromPyObject<'a> for &'a str {
/// Allows extracting strings from Python objects.
/// Accepts Python `str` and `unicode` objects.
impl<'source> FromPyObject<'source> for String {
fn extract(obj: &'source PyObjectRef) -> PyResult<Self> {
fn extract(obj: &'source PyAny) -> PyResult<Self> {
<PyString as PyTryFrom>::try_from(obj)?
.to_string()
.map(Cow::into_owned)

View File

@ -6,7 +6,7 @@ use crate::exceptions;
use crate::ffi::{self, Py_ssize_t};
use crate::instance::{AsPyRef, Py, PyNativeType};
use crate::object::PyObject;
use crate::types::PyObjectRef;
use crate::types::PyAny;
use crate::AsPyPointer;
use crate::IntoPyPointer;
use crate::Python;
@ -72,7 +72,7 @@ impl PyTuple {
/// Gets the item at the specified index.
///
/// Panics if the index is out of range.
pub fn get_item(&self, index: usize) -> &PyObjectRef {
pub fn get_item(&self, index: usize) -> &PyAny {
// TODO: reconsider whether we should panic
// It's quite inconsistent that this method takes `Python` when `len()` does not.
assert!(index < self.len());
@ -111,10 +111,10 @@ pub struct PyTupleIterator<'a> {
}
impl<'a> Iterator for PyTupleIterator<'a> {
type Item = &'a PyObjectRef;
type Item = &'a PyAny;
#[inline]
fn next(&mut self) -> Option<&'a PyObjectRef> {
fn next(&mut self) -> Option<&'a PyAny> {
if self.index < self.slice.len() {
let item = self.slice[self.index].as_ref(self.py);
self.index += 1;
@ -126,7 +126,7 @@ impl<'a> Iterator for PyTupleIterator<'a> {
}
impl<'a> IntoIterator for &'a PyTuple {
type Item = &'a PyObjectRef;
type Item = &'a PyAny;
type IntoIter = PyTupleIterator<'a>;
fn into_iter(self) -> Self::IntoIter {
@ -180,7 +180,7 @@ macro_rules! tuple_conversion ({$length:expr,$(($refN:ident, $n:tt, $T:ident)),+
}
impl<'s, $($T: FromPyObject<'s>),+> FromPyObject<'s> for ($($T,)+) {
fn extract(obj: &'s PyObjectRef) -> PyResult<Self>
fn extract(obj: &'s PyAny) -> PyResult<Self>
{
let t = <PyTuple as PyTryFrom>::try_from(obj)?;
let slice = t.as_slice();
@ -254,7 +254,7 @@ tuple_conversion!(
mod test {
use crate::instance::AsPyRef;
use crate::objectprotocol::ObjectProtocol;
use crate::types::PyObjectRef;
use crate::types::PyAny;
use crate::types::PyTuple;
use crate::Python;
use crate::{PyTryFrom, ToPyObject};
@ -267,7 +267,7 @@ mod test {
let pyob = PyTuple::new(py, &[1, 2, 3]);
let ob = pyob.as_ref(py);
assert_eq!(3, ob.len());
let ob: &PyObjectRef = ob.into();
let ob: &PyAny = ob.into();
assert_eq!((1, 2, 3), ob.extract().unwrap());
let mut map = HashSet::new();
@ -283,7 +283,7 @@ mod test {
let ob = (1, 2, 3).to_object(py);
let tuple = <PyTuple as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
assert_eq!(3, tuple.len());
let ob: &PyObjectRef = tuple.into();
let ob: &PyAny = tuple.into();
assert_eq!((1, 2, 3), ob.extract().unwrap());
}

View File

@ -1,7 +1,7 @@
use pyo3::class::basic::CompareOp;
use pyo3::class::*;
use pyo3::prelude::*;
use pyo3::types::PyObjectRef;
use pyo3::types::PyAny;
#[macro_use]
mod common;
@ -127,35 +127,35 @@ fn inplace_operations() {
#[pyproto]
impl PyNumberProtocol for BinaryArithmetic {
fn __add__(lhs: &PyObjectRef, rhs: &PyObjectRef) -> PyResult<String> {
fn __add__(lhs: &PyAny, rhs: &PyAny) -> PyResult<String> {
Ok(format!("{:?} + {:?}", lhs, rhs))
}
fn __sub__(lhs: &PyObjectRef, rhs: &PyObjectRef) -> PyResult<String> {
fn __sub__(lhs: &PyAny, rhs: &PyAny) -> PyResult<String> {
Ok(format!("{:?} - {:?}", lhs, rhs))
}
fn __mul__(lhs: &PyObjectRef, rhs: &PyObjectRef) -> PyResult<String> {
fn __mul__(lhs: &PyAny, rhs: &PyAny) -> PyResult<String> {
Ok(format!("{:?} * {:?}", lhs, rhs))
}
fn __lshift__(lhs: &PyObjectRef, rhs: &PyObjectRef) -> PyResult<String> {
fn __lshift__(lhs: &PyAny, rhs: &PyAny) -> PyResult<String> {
Ok(format!("{:?} << {:?}", lhs, rhs))
}
fn __rshift__(lhs: &PyObjectRef, rhs: &PyObjectRef) -> PyResult<String> {
fn __rshift__(lhs: &PyAny, rhs: &PyAny) -> PyResult<String> {
Ok(format!("{:?} >> {:?}", lhs, rhs))
}
fn __and__(lhs: &PyObjectRef, rhs: &PyObjectRef) -> PyResult<String> {
fn __and__(lhs: &PyAny, rhs: &PyAny) -> PyResult<String> {
Ok(format!("{:?} & {:?}", lhs, rhs))
}
fn __xor__(lhs: &PyObjectRef, rhs: &PyObjectRef) -> PyResult<String> {
fn __xor__(lhs: &PyAny, rhs: &PyAny) -> PyResult<String> {
Ok(format!("{:?} ^ {:?}", lhs, rhs))
}
fn __or__(lhs: &PyObjectRef, rhs: &PyObjectRef) -> PyResult<String> {
fn __or__(lhs: &PyAny, rhs: &PyAny) -> PyResult<String> {
Ok(format!("{:?} | {:?}", lhs, rhs))
}
}
@ -195,7 +195,7 @@ impl PyObjectProtocol for RichComparisons {
Ok("RC")
}
fn __richcmp__(&self, other: &PyObjectRef, op: CompareOp) -> PyResult<String> {
fn __richcmp__(&self, other: &PyAny, op: CompareOp) -> PyResult<String> {
match op {
CompareOp::Lt => Ok(format!("{} < {:?}", self.__repr__().unwrap(), other)),
CompareOp::Le => Ok(format!("{} <= {:?}", self.__repr__().unwrap(), other)),
@ -216,7 +216,7 @@ impl PyObjectProtocol for RichComparisons2 {
Ok("RC2")
}
fn __richcmp__(&self, _other: &PyObjectRef, op: CompareOp) -> PyResult<PyObject> {
fn __richcmp__(&self, _other: &PyAny, op: CompareOp) -> PyResult<PyObject> {
let gil = GILGuard::acquire();
match op {
CompareOp::Eq => Ok(true.to_object(gil.python())),

View File

@ -2,13 +2,13 @@
use pyo3::ffi::*;
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyObjectRef};
use pyo3::types::{PyAny, PyDict};
fn _get_subclasses<'p>(
py: &'p Python,
py_type: &str,
args: &str,
) -> PyResult<(&'p PyObjectRef, &'p PyObjectRef, &'p PyObjectRef)> {
) -> PyResult<(&'p PyAny, &'p PyAny, &'p PyAny)> {
// Import the class from Python and create some subclasses
let datetime = py.import("datetime")?;

View File

@ -6,7 +6,7 @@ use pyo3::class::{
use pyo3::exceptions::{IndexError, ValueError};
use pyo3::ffi;
use pyo3::prelude::*;
use pyo3::types::{PyBytes, PyDict, PyObjectRef, PySlice, PyString, PyType};
use pyo3::types::{PyAny, PyBytes, PyDict, PySlice, PyString, PyType};
use pyo3::AsPyPointer;
use std::{isize, iter};
@ -351,8 +351,8 @@ impl<'p> PyContextProtocol<'p> for ContextManager {
fn __exit__(
&mut self,
ty: Option<&'p PyType>,
_value: Option<&'p PyObjectRef>,
_traceback: Option<&'p PyObjectRef>,
_value: Option<&'p PyAny>,
_traceback: Option<&'p PyAny>,
) -> PyResult<bool> {
let gil = GILGuard::acquire();
self.exit_called = true;
@ -405,7 +405,7 @@ struct Test {}
#[pyproto]
impl<'p> PyMappingProtocol<'p> for Test {
fn __getitem__(&self, idx: &PyObjectRef) -> PyResult<PyObject> {
fn __getitem__(&self, idx: &PyAny) -> PyResult<PyObject> {
let gil = GILGuard::acquire();
if let Ok(slice) = idx.cast_as::<PySlice>() {
let indices = slice.indices(1000)?;

View File

@ -3,7 +3,7 @@ use pyo3::class::PyTraverseError;
use pyo3::class::PyVisit;
use pyo3::ffi;
use pyo3::prelude::*;
use pyo3::types::PyObjectRef;
use pyo3::types::PyAny;
use pyo3::types::PyTuple;
use pyo3::AsPyPointer;
use pyo3::PyRawObject;
@ -95,7 +95,7 @@ impl Drop for ClassWithDrop {
let _empty1 = PyTuple::empty(py);
let _empty2: PyObject = PyTuple::empty(py).into();
let _empty3: &PyObjectRef = py.from_owned_ptr(ffi::PyTuple_New(0));
let _empty3: &PyAny = py.from_owned_ptr(ffi::PyTuple_New(0));
}
}
}