rename PyObject

This commit is contained in:
Nikolay Kim 2017-06-22 20:56:09 -07:00
parent 2faf18bb9e
commit a58aa7b5e6
37 changed files with 436 additions and 346 deletions

View File

@ -271,7 +271,7 @@ fn wrap_fn(item: &mut syn::Item) -> Option<Box<syn::Block>> {
};
unsafe {
let func = pyo3::PyObjectPtr::from_owned_ptr_or_panic(
let func = pyo3::PyObject::from_owned_ptr_or_panic(
py, pyo3::ffi::PyCFunction_New(
Box::into_raw(Box::new(def.as_method_def())),
std::ptr::null_mut()));

View File

@ -13,7 +13,7 @@ pub fn build_py_class(ast: &mut syn::DeriveInput, attr: String) -> Tokens {
let params = parse_attribute(attr);
let doc = utils::get_doc(&ast.attrs, true);
let base = syn::Ident::from("_pyo3::PyObject");
let base = syn::Ident::from("_pyo3::PyInstance");
let mut token: Option<syn::Ident> = None;
match ast.body {
@ -63,8 +63,8 @@ fn impl_class(cls: &syn::Ident, base: &syn::Ident,
impl _pyo3::ToPyObject for #cls
{
#[inline]
fn to_object<'p>(&self, py: _pyo3::Python<'p>) -> _pyo3::PyObjectPtr {
unsafe { _pyo3::PyObjectPtr::from_borrowed_ptr(py, self.as_ptr()) }
fn to_object<'p>(&self, py: _pyo3::Python<'p>) -> _pyo3::PyObject {
unsafe { _pyo3::PyObject::from_borrowed_ptr(py, self.as_ptr()) }
}
#[inline]
@ -77,12 +77,12 @@ fn impl_class(cls: &syn::Ident, base: &syn::Ident,
impl<'a> _pyo3::IntoPyObject for &'a #cls
{
#[inline]
fn into_object<'p>(self, py: _pyo3::Python) -> _pyo3::PyObjectPtr {
unsafe { _pyo3::PyObjectPtr::from_borrowed_ptr(py, self.as_ptr()) }
fn into_object<'p>(self, py: _pyo3::Python) -> _pyo3::PyObject {
unsafe { _pyo3::PyObject::from_borrowed_ptr(py, self.as_ptr()) }
}
}
impl std::convert::AsRef<PyObject> for #cls {
fn as_ref(&self) -> &_pyo3::PyObject {
impl std::convert::AsRef<PyInstance> for #cls {
fn as_ref(&self) -> &_pyo3::PyInstance {
unsafe{std::mem::transmute(self.as_ptr())}
}
}
@ -201,7 +201,7 @@ fn impl_class(cls: &syn::Ident, base: &syn::Ident,
impl _pyo3::PyDowncastFrom for #cls
{
fn downcast_from(ob: &_pyo3::PyObject) -> Result<&#cls, _pyo3::PyDowncastError>
fn downcast_from(ob: &_pyo3::PyInstance) -> Result<&#cls, _pyo3::PyDowncastError>
{
unsafe {
let checked = ffi::PyObject_TypeCheck(
@ -217,13 +217,13 @@ fn impl_class(cls: &syn::Ident, base: &syn::Ident,
}
}
unsafe fn unchecked_downcast_from(ob: &_pyo3::PyObject) -> &Self
unsafe fn unchecked_downcast_from(ob: &_pyo3::PyInstance) -> &Self
{
let offset = <#cls as _pyo3::typeob::PyTypeInfo>::offset();
let ptr = (ob.as_ptr() as *mut u8).offset(offset) as *mut #cls;
std::mem::transmute(ptr)
}
unsafe fn unchecked_mut_downcast_from(ob: &_pyo3::PyObject) -> &mut Self
unsafe fn unchecked_mut_downcast_from(ob: &_pyo3::PyInstance) -> &mut Self
{
let offset = <#cls as _pyo3::typeob::PyTypeInfo>::offset();
let ptr = (ob.as_ptr() as *mut u8).offset(offset) as *mut #cls;
@ -232,7 +232,7 @@ fn impl_class(cls: &syn::Ident, base: &syn::Ident,
}
impl _pyo3::PyMutDowncastFrom for #cls
{
fn downcast_mut_from(ob: &mut _pyo3::PyObject)
fn downcast_mut_from(ob: &mut _pyo3::PyInstance)
-> Result<&mut #cls, _pyo3::PyDowncastError>
{
unsafe {

View File

@ -5,7 +5,7 @@
use ffi;
use python::Python;
use objects::{PyObject, PyTuple, PyDict, PyString, exc};
use objects::{PyInstance, PyTuple, PyDict, PyString, exc};
//use conversion::RefFromPyObject;
use err::{self, PyResult};
@ -31,7 +31,7 @@ pub fn parse_args<'p>(py: Python<'p>,
fname: Option<&str>, params: &[ParamDescription],
args: &'p PyTuple, kwargs: Option<&'p PyDict>,
accept_args: bool, accept_kwargs: bool,
output: &mut[Option<&'p PyObject>]) -> PyResult<()>
output: &mut[Option<&'p PyInstance>]) -> PyResult<()>
{
@ -106,7 +106,7 @@ pub unsafe fn get_kwargs<'p>(py: Python<'p>, ptr: *mut ffi::PyObject) -> Option<
/*#[doc(hidden)] // used in py_argparse_extract!() macro
pub fn with_extracted_or_default<P: ?Sized, R, F>(
py: Python, obj: Option<&PyObject>, f: F, default: &'static P) -> PyResult<R>
py: Python, obj: Option<&PyInstance>, f: F, default: &'static P) -> PyResult<R>
where F: FnOnce(&P) -> PyResult<R>,
P: RefFromPyObject
{

View File

@ -25,7 +25,7 @@ use ffi;
use exc;
use err::{self, PyResult};
use python::{Python, ToPyPointer};
use objects::PyObject;
use objects::PyInstance;
/// Allows access to the underlying buffer used by a python object such as `bytes`, `bytearray` or `array.array`.
pub struct PyBuffer(Box<ffi::Py_buffer>); // use Box<> because Python expects that the Py_buffer struct has a stable memory address
@ -138,7 +138,7 @@ fn validate(b: &ffi::Py_buffer) {
impl PyBuffer {
/// Get the underlying buffer from the specified python object.
pub fn get(py: Python, obj: &PyObject) -> PyResult<PyBuffer> {
pub fn get(py: Python, obj: &PyInstance) -> PyResult<PyBuffer> {
unsafe {
let mut buf = Box::new(mem::zeroed::<ffi::Py_buffer>());
err::error_on_minusone(

View File

@ -14,7 +14,7 @@ use ffi;
use callback;
use err::{PyErr, PyResult};
use python::{Python, IntoPyPointer, PyDowncastFrom};
use objects::{exc, PyObject};
use objects::{exc, PyInstance};
use typeob::PyTypeInfo;
use conversion::{FromPyObject, IntoPyObject};
use objectprotocol::ObjectProtocol;
@ -368,7 +368,7 @@ impl<T> PyObjectRichcmpProtocolImpl for T
callback::cb_meth(LOCATION, |py| {
let slf = py.cast_from_borrowed_ptr::<T>(slf);
let arg = py.cast_from_borrowed_ptr::<PyObject>(arg);
let arg = py.cast_from_borrowed_ptr::<PyInstance>(arg);
let res = match extract_op(py, op) {
Ok(op) => match arg.extract() {

View File

@ -10,7 +10,7 @@ use std::os::raw::c_int;
use ffi;
use err::PyResult;
use python::PyDowncastFrom;
use objects::{PyType, PyObject};
use objects::{PyType, PyInstance};
use callback::{PyObjectCallbackConverter, UnitCallbackConverter};
use typeob::PyTypeInfo;
use class::methods::PyMethodDef;
@ -21,16 +21,16 @@ use conversion::{IntoPyObject, FromPyObject};
#[allow(unused_variables)]
pub trait PyDescrProtocol<'p>: PyTypeInfo + PyDowncastFrom {
fn __get__(&'p self, instance: &'p PyObject, owner: Option<&'p PyType>)
fn __get__(&'p self, instance: &'p PyInstance, owner: Option<&'p PyType>)
-> Self::Result where Self: PyDescrGetProtocol<'p> { unimplemented!() }
fn __set__(&'p self, instance: &'p PyObject, value: &'p PyObject)
fn __set__(&'p self, instance: &'p PyInstance, value: &'p PyInstance)
-> Self::Result where Self: PyDescrSetProtocol<'p> { unimplemented!() }
fn __delete__(&'p self, instance: &'p PyObject)
fn __delete__(&'p self, instance: &'p PyInstance)
-> Self::Result where Self: PyDescrDeleteProtocol<'p> { unimplemented!() }
fn __set_name__(&'p self, instance: &'p PyObject)
fn __set_name__(&'p self, instance: &'p PyInstance)
-> Self::Result where Self: PyDescrSetNameProtocol<'p> { unimplemented!() }
}

View File

@ -78,7 +78,7 @@ macro_rules! py_binary_func{
$crate::callback::cb_pyfunc::<_, _, $res_type>(LOCATION, $conv, |py| {
let slf = py.mut_cast_from_borrowed_ptr::<T>(slf);
let arg = py.cast_from_borrowed_ptr::<$crate::PyObject>(arg);
let arg = py.cast_from_borrowed_ptr::<$crate::PyInstance>(arg);
let result = match arg.extract() {
Ok(arg) => slf.$f(arg).into(),
@ -105,7 +105,7 @@ macro_rules! py_binary_self_func{
$crate::callback::cb_meth(LOCATION, |py| {
let slf1 = py.mut_cast_from_borrowed_ptr::<T>(slf);
let arg = py.cast_from_borrowed_ptr::<$crate::PyObject>(arg);
let arg = py.cast_from_borrowed_ptr::<$crate::PyInstance>(arg);
let result = match arg.extract() {
Ok(arg) => slf1.$f(arg).into(),
@ -166,8 +166,8 @@ macro_rules! py_ternary_func{
$crate::callback::cb_pyfunc::<_, _, $res_type>(LOCATION, $conv, |py| {
let slf = py.mut_cast_from_borrowed_ptr::<T>(slf);
let arg1 = py.cast_from_borrowed_ptr::<$crate::PyObject>(arg1);
let arg2 = py.cast_from_borrowed_ptr::<$crate::PyObject>(arg2);
let arg1 = py.cast_from_borrowed_ptr::<$crate::PyInstance>(arg1);
let arg2 = py.cast_from_borrowed_ptr::<$crate::PyInstance>(arg2);
let result = match arg1.extract() {
Ok(arg1) => match arg2.extract() {
@ -199,8 +199,8 @@ macro_rules! py_ternary_self_func{
$crate::callback::cb_meth(LOCATION, |py| {
let slf1 = py.mut_cast_from_borrowed_ptr::<T>(slf);
let arg1 = py.cast_from_borrowed_ptr::<$crate::PyObject>(arg1);
let arg2 = py.cast_from_borrowed_ptr::<$crate::PyObject>(arg2);
let arg1 = py.cast_from_borrowed_ptr::<$crate::PyInstance>(arg1);
let arg2 = py.cast_from_borrowed_ptr::<$crate::PyInstance>(arg2);
let result = match arg1.extract() {
Ok(arg1) => match arg2.extract() {
@ -242,8 +242,8 @@ macro_rules! py_func_set{
e.restore(py);
-1
} else {
let name = py.mut_cast_from_borrowed_ptr::<$crate::PyObject>(name);
let value = py.cast_from_borrowed_ptr::<$crate::PyObject>(value);
let name = py.mut_cast_from_borrowed_ptr::<$crate::PyInstance>(name);
let value = py.cast_from_borrowed_ptr::<$crate::PyInstance>(value);
let result = match name.extract() {
Ok(name) => match value.extract() {
Ok(value) =>
@ -287,7 +287,7 @@ macro_rules! py_func_del{
{
if value.is_null() {
let slf = py.mut_cast_from_borrowed_ptr::<T>(slf);
let name = py.cast_from_borrowed_ptr::<$crate::PyObject>(name);
let name = py.cast_from_borrowed_ptr::<$crate::PyInstance>(name);
let result = match name.extract() {
Ok(name) => slf.$f(name).into(),
@ -331,7 +331,7 @@ macro_rules! py_func_set_del{
LOCATION, $crate::callback::UnitCallbackConverter, |py|
{
let slf = py.mut_cast_from_borrowed_ptr::<T>(slf);
let name = py.cast_from_borrowed_ptr::<$crate::PyObject>(name);
let name = py.cast_from_borrowed_ptr::<$crate::PyInstance>(name);
if value.is_null() {
let result = match name.extract() {
@ -346,7 +346,7 @@ macro_rules! py_func_set_del{
}
}
} else {
let value = py.cast_from_borrowed_ptr::<$crate::PyObject>(value);
let value = py.cast_from_borrowed_ptr::<$crate::PyInstance>(value);
let result = match name.extract() {
Ok(name) => match value.extract() {
Ok(value) => {

View File

@ -8,7 +8,7 @@ use std::os::raw::c_int;
use ffi;
use python::PyDowncastFrom;
use err::{PyErr, PyResult};
use objects::{exc, PyObject};
use objects::{exc, PyInstance};
use objectprotocol::ObjectProtocol;
use callback::{PyObjectCallbackConverter, LenResultConverter, BoolCallbackConverter};
use typeob::PyTypeInfo;
@ -225,7 +225,7 @@ impl<T> PySequenceSetItemProtocolImpl for T
e.restore(py);
-1
} else {
let value = py.cast_from_borrowed_ptr::<PyObject>(value);
let value = py.cast_from_borrowed_ptr::<PyInstance>(value);
let result = match value.extract() {
Ok(value) => {
slf.__setitem__(key as isize, value).into()
@ -314,7 +314,7 @@ impl<T> PySequenceDelItemProtocolImpl for T
}
}
} else {
let value = py.cast_from_borrowed_ptr::<PyObject>(value);
let value = py.cast_from_borrowed_ptr::<PyInstance>(value);
let result = match value.extract() {
Ok(value) => {
slf.__setitem__(key as isize, value).into()

View File

@ -1,8 +1,8 @@
use ffi;
use err::PyResult;
use python::{Python, ToPyPointer, PyDowncastFrom};
use pointer::PyObjectPtr;
use objects::{PyObject, PyTuple};
use pointer::PyObject;
use objects::{PyInstance, PyTuple};
use objectprotocol::ObjectProtocol;
use typeob::PyTypeInfo;
use instance::Py;
@ -12,7 +12,7 @@ use instance::Py;
pub trait ToPyObject {
/// Converts self into a Python object.
fn to_object(&self, py: Python) -> PyObjectPtr;
fn to_object(&self, py: Python) -> PyObject;
/// Converts self into a Python object and calls the specified closure
/// on the native FFI pointer underlying the Python object.
@ -34,7 +34,7 @@ pub trait IntoPyObject {
/// Converts self into a Python object. (Consumes self)
#[inline]
fn into_object(self, py: Python) -> PyObjectPtr
fn into_object(self, py: Python) -> PyObject
where Self: Sized;
}
@ -70,11 +70,11 @@ pub trait IntoPyTuple {
/// the inherent method `PyObject::extract()` can be used.
pub trait FromPyObject<'source> : Sized {
/// Extracts `Self` from the source `PyObject`.
fn extract(ob: &'source PyObject) -> PyResult<Self>;
fn extract(ob: &'source PyInstance) -> PyResult<Self>;
}
pub trait RefFromPyObject {
fn with_extracted<F, R>(ob: &PyObject, f: F) -> PyResult<R>
fn with_extracted<F, R>(ob: &PyInstance, f: F) -> PyResult<R>
where F: FnOnce(&Self) -> R;
}
@ -82,7 +82,7 @@ impl <T: ?Sized> RefFromPyObject for T
where for<'a> &'a T: FromPyObject<'a> + Sized
{
#[inline]
fn with_extracted<F, R>(obj: &PyObject, f: F) -> PyResult<R>
fn with_extracted<F, R>(obj: &PyInstance, f: F) -> PyResult<R>
where F: FnOnce(&Self) -> R
{
match FromPyObject::extract(obj) {
@ -97,7 +97,7 @@ impl <T: ?Sized> RefFromPyObject for T
impl <'a, T: ?Sized> ToPyObject for &'a T where T: ToPyObject {
#[inline]
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
<T as ToPyObject>::to_object(*self, py)
}
@ -113,7 +113,7 @@ impl <'a, T: ?Sized> ToPyObject for &'a T where T: ToPyObject {
/// `Option::None` is converted to Python `None`.
impl <T> ToPyObject for Option<T> where T: ToPyObject {
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
match *self {
Some(ref val) => val.to_object(py),
None => py.None(),
@ -122,7 +122,7 @@ impl <T> ToPyObject for Option<T> where T: ToPyObject {
}
impl<T> IntoPyObject for Option<T> where T: IntoPyObject {
fn into_object(self, py: Python) -> PyObjectPtr {
fn into_object(self, py: Python) -> PyObject {
match self {
Some(val) => val.into_object(py),
None => py.None(),
@ -132,12 +132,12 @@ impl<T> IntoPyObject for Option<T> where T: IntoPyObject {
/// `()` is converted to Python `None`.
impl ToPyObject for () {
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
py.None()
}
}
impl IntoPyObject for () {
fn into_object(self, py: Python) -> PyObjectPtr {
fn into_object(self, py: Python) -> PyObject {
py.None()
}
}
@ -147,7 +147,7 @@ impl<'a, T> FromPyObject<'a> for &'a T
where T: PyTypeInfo + PyDowncastFrom
{
#[inline]
default fn extract(ob: &'a PyObject) -> PyResult<&'a T>
default fn extract(ob: &'a PyInstance) -> PyResult<&'a T>
{
Ok(ob.cast_as()?)
}
@ -155,7 +155,7 @@ impl<'a, T> FromPyObject<'a> for &'a T
impl<'source, T> FromPyObject<'source> for Option<T> where T: FromPyObject<'source>
{
fn extract(obj: &'source PyObject) -> PyResult<Self>
fn extract(obj: &'source PyInstance) -> PyResult<Self>
{
if obj.as_ptr() == unsafe { ffi::Py_None() } {
Ok(None)

View File

@ -7,8 +7,8 @@ use libc;
use ffi;
use python::{ToPyPointer, IntoPyPointer, Python, PyClone};
use PyObjectPtr;
use objects::{PyObject, PyType, exc};
use PyObject;
use objects::{PyInstance, PyType, exc};
use instance::Py;
use typeob::PyTypeObject;
use conversion::{ToPyObject, IntoPyTuple, IntoPyObject};
@ -99,9 +99,9 @@ pub struct PyErr {
/// a tuple of arguments to be passed to `ptype`'s constructor,
/// or a single argument to be passed to `ptype`'s constructor.
/// Call `PyErr::instance()` to get the exception instance in all cases.
pub pvalue: Option<PyObjectPtr>,
pub pvalue: Option<PyObject>,
/// The `PyTraceBack` object associated with the error.
pub ptraceback: Option<PyObjectPtr>,
pub ptraceback: Option<PyObject>,
}
@ -143,7 +143,7 @@ impl PyErr {
/// `base` can be an existing exception type to subclass, or a tuple of classes
/// `dict` specifies an optional dictionary of class variables and methods
pub fn new_type<'p>(py: Python<'p>,
name: &str, base: Option<&PyType>, dict: Option<PyObjectPtr>)
name: &str, base: Option<&PyType>, dict: Option<PyObject>)
-> &'p PyType
{
let base: *mut ffi::PyObject = match base {
@ -190,12 +190,12 @@ impl PyErr {
} else {
PyType::from_type_ptr(py, ptype as *mut ffi::PyTypeObject).into()
},
pvalue: PyObjectPtr::from_owned_ptr_or_opt(py, pvalue),
ptraceback: PyObjectPtr::from_owned_ptr_or_opt(py, ptraceback)
pvalue: PyObject::from_owned_ptr_or_opt(py, pvalue),
ptraceback: PyObject::from_owned_ptr_or_opt(py, ptraceback)
}
}
fn new_helper(_py: Python, ty: &PyType, value: PyObjectPtr) -> PyErr {
fn new_helper(_py: Python, ty: &PyType, value: PyObject) -> PyErr {
assert!(unsafe { ffi::PyExceptionClass_Check(ty.as_ptr()) } != 0);
PyErr {
ptype: ty.into(),
@ -213,7 +213,7 @@ impl PyErr {
PyErr::from_instance_helper(py, obj.into_object(py))
}
fn from_instance_helper<'p>(py: Python, obj: PyObjectPtr) -> PyErr {
fn from_instance_helper<'p>(py: Python, obj: PyObject) -> PyErr {
let ptr = obj.as_ptr();
if unsafe { ffi::PyExceptionInstance_Check(ptr) } != 0 {
@ -241,7 +241,7 @@ impl PyErr {
/// `exc` is the exception type; usually one of the standard exceptions like `py.get_type::<exc::RuntimeError>()`.
/// `value` is the exception instance, or a tuple of arguments to pass to the exception constructor.
#[inline]
pub fn new_lazy_init(exc: &PyType, value: Option<PyObjectPtr>) -> PyErr {
pub fn new_lazy_init(exc: &PyType, value: Option<PyObject>) -> PyErr {
PyErr {
ptype: exc.into(),
pvalue: value,
@ -317,7 +317,7 @@ impl PyErr {
/// Retrieves the exception instance for this error.
/// This method takes `&mut self` because the error might need
/// to be normalized in order to create the exception instance.
pub fn instance(&mut self, py: Python) -> PyObjectPtr {
pub fn instance(&mut self, py: Python) -> PyObject {
self.normalize(py);
match self.pvalue {
Some(ref instance) => instance.clone_ref(py),
@ -337,7 +337,7 @@ impl PyErr {
/// Issue a warning message.
/// May return a PyErr if warnings-as-errors is enabled.
pub fn warn(py: Python, category: &PyObject, message: &str, stacklevel: i32) -> PyResult<()> {
pub fn warn(py: Python, category: &PyInstance, message: &str, stacklevel: i32) -> PyResult<()> {
let message = CString::new(message).map_err(|e| e.to_pyerr(py))?;
unsafe {
error_on_minusone(py, ffi::PyErr_WarnEx(

View File

@ -6,9 +6,10 @@ use std::marker::PhantomData;
use ffi;
use err::{PyResult, PyErr, PyDowncastError};
use pointer::PyObjectPtr;
use objects::PyObject;
use conversion::{ToPyObject, IntoPyObject};
use pointer::PyObject;
use objects::PyInstance;
use objectprotocol::ObjectProtocol;
use conversion::{ToPyObject, IntoPyObject, FromPyObject};
use python::{Python, IntoPyPointer, ToPyPointer, PyDowncastInto};
use typeob::{PyTypeInfo, PyObjectAlloc};
@ -134,12 +135,6 @@ impl<T> Py<T> {
unsafe { ffi::Py_REFCNT(self.0) }
}
/// Get reference to &PyObject.
#[inline]
pub fn as_object<'p>(&self, _py: Python<'p>) -> &PyObject {
unsafe { std::mem::transmute(self) }
}
/// Clone self, Calls Py_INCREF() on the ptr.
#[inline]
pub fn clone_ref(&self, _py: Python) -> Py<T> {
@ -214,9 +209,9 @@ impl<T> AsPyRef<T> for Py<T> where T: PyTypeInfo + PyNativeType {
}
impl<T> ToPyObject for Py<T> {
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
unsafe {
PyObjectPtr::from_borrowed_ptr(py, self.as_ptr())
PyObject::from_borrowed_ptr(py, self.as_ptr())
}
}
}
@ -225,7 +220,7 @@ impl<T> IntoPyObject for Py<T> {
/// Converts `Py` instance -> PyObject.
/// Consumes `self` without calling `Py_DECREF()`
#[inline]
fn into_object(self, _py: Python) -> PyObjectPtr {
fn into_object(self, _py: Python) -> PyObject {
unsafe { std::mem::transmute(self) }
}
}
@ -268,7 +263,7 @@ impl<T> Drop for Py<T> {
}
impl<T> std::convert::From<Py<T>> for PyObjectPtr {
impl<T> std::convert::From<Py<T>> for PyObject {
#[inline]
fn from(ob: Py<T>) -> Self {
unsafe {std::mem::transmute(ob)}
@ -291,7 +286,7 @@ impl<'a, T> std::convert::From<&'a mut T> for Py<T>
}
}
impl<'a, T> std::convert::From<&'a T> for PyObjectPtr
impl<'a, T> std::convert::From<&'a T> for PyObject
where T: ToPyPointer,
{
fn from(ob: &'a T) -> Self {
@ -299,7 +294,7 @@ impl<'a, T> std::convert::From<&'a T> for PyObjectPtr
}
}
impl<'a, T> std::convert::From<&'a mut T> for PyObjectPtr
impl<'a, T> std::convert::From<&'a mut T> for PyObject
where T: ToPyPointer,
{
fn from(ob: &'a mut T) -> Self {
@ -345,3 +340,15 @@ impl<T> PyDowncastInto for Py<T> where T: PyTypeInfo
}
}
}
impl<'a, T> FromPyObject<'a> for Py<T> where T: ToPyPointer + FromPyObject<'a>
{
/// Extracts `Self` from the source `PyObject`.
fn extract(ob: &'a PyInstance) -> PyResult<Self>
{
unsafe {
ob.extract::<T>().map(|val| Py::from_borrowed_ptr(val.as_ptr()))
}
}
}

View File

@ -155,7 +155,7 @@ pub use ffi::{Py_ssize_t, Py_hash_t};
pub use err::{PyErr, PyResult, PyDowncastError, ToPyErr};
pub use objects::*;
pub use objectprotocol::ObjectProtocol;
pub use pointer::PyObjectPtr;
pub use pointer::PyObject;
pub use python::{Python, ToPyPointer, IntoPyPointer, PyClone,
PyMutDowncastFrom, PyDowncastFrom, PyDowncastInto};
pub use pythonrun::{GILGuard, prepare_freethreaded_python};

View File

@ -6,9 +6,9 @@ use std::os::raw::c_int;
use ffi;
use err::{PyErr, PyResult, PyDowncastError, self};
use python::{Python, ToPyPointer, PyDowncastFrom};
use pointer::PyObjectPtr;
use objects::{PyObject, PyDict, PyString, PyIterator, PyType};
use python::{Python, ToPyPointer, PyDowncastFrom, PyClone};
use pointer::PyObject;
use objects::{PyInstance, PyDict, PyString, PyIterator, PyType};
use conversion::{ToPyObject, IntoPyTuple, FromPyObject};
use instance::PyObjectWithToken;
@ -21,7 +21,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<&PyObject> where N: ToPyObject;
fn getattr<N>(&self, attr_name: N) -> PyResult<&PyInstance> where N: ToPyObject;
/// Sets an attribute value.
/// This is equivalent to the Python expression 'self.attr_name = value'.
@ -58,7 +58,7 @@ pub trait ObjectProtocol {
/// * CompareOp::Le: `self <= other`
/// * CompareOp::Gt: `self > other`
/// * CompareOp::Ge: `self >= other`
fn rich_compare<O>(&self, other: O, compare_op: ::CompareOp) -> PyResult<PyObjectPtr>
fn rich_compare<O>(&self, other: O, compare_op: ::CompareOp) -> PyResult<PyObject>
where O: ToPyObject;
/// Compute the string representation of self.
@ -74,13 +74,13 @@ pub trait ObjectProtocol {
/// Calls the object.
/// This is equivalent to the Python expression: 'self(*args, **kwargs)'
fn call<A>(&self, args: A, kwargs: Option<&PyDict>) -> PyResult<&PyObject>
fn call<A>(&self, args: A, kwargs: Option<&PyDict>) -> PyResult<&PyInstance>
where A: IntoPyTuple;
/// Calls a method on the object.
/// This is equivalent to the Python expression: 'self.name(*args, **kwargs)'
fn call_method<A>(&self, name: &str, args: A, kwargs: Option<&PyDict>)
-> PyResult<&PyObject>
-> PyResult<&PyInstance>
where A: IntoPyTuple;
/// Retrieves the hash code of the object.
@ -101,7 +101,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<&PyObject> where K: ToPyObject;
fn get_item<K>(&self, key: K) -> PyResult<&PyInstance> where K: ToPyObject;
/// Sets an item value.
/// This is equivalent to the Python expression 'self[key] = value'.
@ -124,18 +124,25 @@ pub trait ObjectProtocol {
/// Fails with `PyDowncastError` if the object is not of the expected type.
fn cast_as<'a, D>(&'a self) -> Result<&'a D, PyDowncastError<'a>>
where D: PyDowncastFrom,
&'a PyObject: std::convert::From<&'a Self>;
&'a PyInstance: std::convert::From<&'a Self>;
/// Extracts some type from the Python object.
/// This is a wrapper function around `FromPyObject::extract()`.
#[inline]
fn extract<'a, D>(&'a self) -> PyResult<D>
where D: FromPyObject<'a>,
&'a PyObject: std::convert::From<&'a Self>;
&'a PyInstance: std::convert::From<&'a Self>;
/// Returns reference count for python object.
fn get_refcnt(&self) -> isize;
/// Clones PyObject. (utility function)
fn clone_ref(&self, ptr: PyObject) -> PyObject;
/// Gets the Python builtin value `None`.
#[allow(non_snake_case)] // the Python keyword starts with uppercase
fn None(&self) -> PyObject;
}
@ -149,7 +156,7 @@ impl<T> ObjectProtocol for T where T: PyObjectWithToken + ToPyPointer {
}
#[inline]
fn getattr<N>(&self, attr_name: N) -> PyResult<&PyObject> where N: ToPyObject
fn getattr<N>(&self, attr_name: N) -> PyResult<&PyInstance> where N: ToPyObject
{
attr_name.with_borrowed_ptr(self.token(), |attr_name| unsafe {
self.token().cast_from_ptr_or_err(
@ -208,10 +215,10 @@ impl<T> ObjectProtocol for T where T: PyObjectWithToken + ToPyPointer {
}
fn rich_compare<O>(&self, other: O, compare_op: ::CompareOp)
-> PyResult<PyObjectPtr> where O: ToPyObject {
-> PyResult<PyObject> where O: ToPyObject {
unsafe {
other.with_borrowed_ptr(self.token(), |other| {
PyObjectPtr::from_owned_ptr_or_err(
PyObject::from_owned_ptr_or_err(
self.token(), ffi::PyObject_RichCompare(
self.as_ptr(), other, compare_op as c_int))
})
@ -240,7 +247,7 @@ impl<T> ObjectProtocol for T where T: PyObjectWithToken + ToPyPointer {
}
#[inline]
fn call<A>(&self, args: A, kwargs: Option<&PyDict>) -> PyResult<&PyObject>
fn call<A>(&self, args: A, kwargs: Option<&PyDict>) -> PyResult<&PyInstance>
where A: IntoPyTuple
{
let t = args.into_tuple(self.token());
@ -254,7 +261,7 @@ impl<T> ObjectProtocol for T where T: PyObjectWithToken + ToPyPointer {
#[inline]
fn call_method<A>(&self, name: &str, args: A, kwargs: Option<&PyDict>)
-> PyResult<&PyObject>
-> PyResult<&PyInstance>
where A: IntoPyTuple
{
name.with_borrowed_ptr(self.token(), |name| unsafe {
@ -303,7 +310,7 @@ impl<T> ObjectProtocol for T where T: PyObjectWithToken + ToPyPointer {
}
#[inline]
fn get_item<K>(&self, key: K) -> PyResult<&PyObject> where K: ToPyObject {
fn get_item<K>(&self, key: K) -> PyResult<&PyInstance> where K: ToPyObject {
key.with_borrowed_ptr(self.token(), |key| unsafe {
self.token().cast_from_ptr_or_err(
ffi::PyObject_GetItem(self.as_ptr(), key))
@ -333,7 +340,7 @@ impl<T> ObjectProtocol for T where T: PyObjectWithToken + ToPyPointer {
#[inline]
fn iter<'p>(&'p self) -> PyResult<PyIterator<'p>> {
unsafe {
let ptr = PyObjectPtr::from_owned_ptr_or_err(
let ptr = PyObject::from_owned_ptr_or_err(
self.token(), ffi::PyObject_GetIter(self.as_ptr()))?;
PyIterator::from_object(self.token(), ptr).map_err(|e| e.into())
}
@ -349,7 +356,7 @@ impl<T> ObjectProtocol for T where T: PyObjectWithToken + ToPyPointer {
#[inline]
fn cast_as<'a, D>(&'a self) -> Result<&'a D, PyDowncastError<'a>>
where D: PyDowncastFrom,
&'a PyObject: std::convert::From<&'a Self>
&'a PyInstance: std::convert::From<&'a Self>
{
<D as PyDowncastFrom>::downcast_from(self.into())
}
@ -357,11 +364,21 @@ impl<T> ObjectProtocol for T where T: PyObjectWithToken + ToPyPointer {
#[inline]
fn extract<'a, D>(&'a self) -> PyResult<D>
where D: FromPyObject<'a>,
&'a PyObject: std::convert::From<&'a T>
&'a PyInstance: std::convert::From<&'a T>
{
FromPyObject::extract(self.into())
}
fn clone_ref(&self, ptr: PyObject) -> PyObject {
ptr.clone_ref(self.token())
}
#[allow(non_snake_case)] // the Python keyword starts with uppercase
#[inline]
fn None(&self) -> PyObject {
unsafe { PyObject::from_borrowed_ptr(self.token(), ffi::Py_None()) }
}
fn get_refcnt(&self) -> isize {
unsafe { ffi::Py_REFCNT(self.as_ptr()) }
}

View File

@ -1,10 +1,10 @@
use ffi;
use pointer::PyObjectPtr;
use pointer::PyObject;
use python::{ToPyPointer, Python};
use conversion::{ToPyObject, IntoPyObject};
/// Represents a Python `bool`.
pub struct PyBool(PyObjectPtr);
pub struct PyBool(PyObject);
pyobject_convert!(PyBool);
pyobject_nativetype!(PyBool, PyBool_Type, PyBool_Check);
@ -29,9 +29,9 @@ impl PyBool {
/// Converts a rust `bool` to a Python `bool`.
impl ToPyObject for bool {
#[inline]
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
unsafe {
PyObjectPtr::from_borrowed_ptr(
PyObject::from_borrowed_ptr(
py,
if *self { ffi::Py_True() } else { ffi::Py_False() })
}
@ -48,7 +48,7 @@ impl ToPyObject for bool {
impl IntoPyObject for bool {
#[inline]
fn into_object(self, py: Python) -> PyObjectPtr {
fn into_object(self, py: Python) -> PyObject {
PyBool::new(py, self).into()
}
}
@ -64,7 +64,7 @@ pyobject_extract!(py, obj to bool => {
#[cfg(test)]
mod test {
use python::Python;
use objects::PyObject;
use objects::PyInstance;
use conversion::ToPyObject;
use objectprotocol::ObjectProtocol;
@ -73,7 +73,7 @@ mod test {
let gil = Python::acquire_gil();
let py = gil.python();
assert!(py.True().is_true());
let t: &PyObject = py.True().into();
let t: &PyInstance = py.True().into();
assert_eq!(true, t.extract().unwrap());
assert!(true.to_object(py) == py.True().into());
}
@ -83,7 +83,7 @@ mod test {
let gil = Python::acquire_gil();
let py = gil.python();
assert!(!py.False().is_true());
let t: &PyObject = py.False().into();
let t: &PyInstance = py.False().into();
assert_eq!(false, t.extract().unwrap());
assert!(false.to_object(py) == py.False().into());
}

View File

@ -3,13 +3,13 @@
use std;
use std::os::raw::c_char;
use ffi;
use pointer::PyObjectPtr;
use pointer::PyObject;
use instance::PyObjectWithToken;
use python::{Python, ToPyPointer};
use err::{PyResult, PyErr};
/// Represents a Python bytearray.
pub struct PyByteArray(PyObjectPtr);
pub struct PyByteArray(PyObject);
pyobject_convert!(PyByteArray);
pyobject_nativetype!(PyByteArray, PyByteArray_Type, PyByteArray_Check);
@ -75,7 +75,7 @@ impl PyByteArray {
mod test {
use exc;
use python::Python;
use pointer::PyObjectPtr;
use pointer::PyObject;
use objects::PyByteArray;
#[test]
@ -88,7 +88,7 @@ mod test {
assert_eq!(src.len(), bytearray.len());
assert_eq!(src, bytearray.data());
let ba: PyObjectPtr = bytearray.into();
let ba: PyObject = bytearray.into();
let bytearray = PyByteArray::from(py, ba).unwrap();
assert_eq!(src.len(), bytearray.len());

View File

@ -5,15 +5,15 @@
use std::{mem, collections, hash, cmp};
use ffi;
use pointer::PyObjectPtr;
use pointer::PyObject;
use instance::PyObjectWithToken;
use python::{Python, ToPyPointer};
use conversion::ToPyObject;
use objects::{PyObject, PyList};
use objects::{PyInstance, PyList};
use err::{self, PyResult, PyErr};
/// Represents a Python `dict`.
pub struct PyDict(PyObjectPtr);
pub struct PyDict(PyObject);
pyobject_convert!(PyDict);
pyobject_nativetype!(PyDict, PyDict_Type, PyDict_Check);
@ -64,7 +64,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<&PyObject> where K: ToPyObject {
pub fn get_item<K>(&self, key: K) -> Option<&PyInstance> where K: ToPyObject {
key.with_borrowed_ptr(self.token(), |key| unsafe {
self.token().cast_from_borrowed_ptr_or_opt(
ffi::PyDict_GetItem(self.as_ptr(), key))
@ -104,7 +104,7 @@ impl PyDict {
}
/// Returns the list of (key, value) pairs in this dictionary.
pub fn items(&self) -> Vec<(PyObjectPtr, PyObjectPtr)> {
pub fn items(&self) -> Vec<(PyObject, PyObject)> {
// Note that we don't provide an iterator because
// PyDict_Next() is unsafe to use when the dictionary might be changed
// by other python code.
@ -114,8 +114,8 @@ impl PyDict {
let mut key: *mut ffi::PyObject = mem::uninitialized();
let mut value: *mut ffi::PyObject = mem::uninitialized();
while ffi::PyDict_Next(self.as_ptr(), &mut pos, &mut key, &mut value) != 0 {
vec.push((PyObjectPtr::from_borrowed_ptr(self.token(), key),
PyObjectPtr::from_borrowed_ptr(self.token(), value)));
vec.push((PyObject::from_borrowed_ptr(self.token(), key),
PyObject::from_borrowed_ptr(self.token(), value)));
}
}
vec
@ -126,7 +126,7 @@ impl <K, V> ToPyObject for collections::HashMap<K, V>
where K: hash::Hash+cmp::Eq+ToPyObject,
V: ToPyObject
{
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
let dict = PyDict::new(py);
for (key, value) in self {
dict.set_item(key, value).expect("Failed to set_item on dict");
@ -139,7 +139,7 @@ impl <K, V> ToPyObject for collections::BTreeMap<K, V>
where K: cmp::Eq+ToPyObject,
V: ToPyObject
{
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
let dict = PyDict::new(py);
for (key, value) in self {
dict.set_item(key, value).expect("Failed to set_item on dict");

View File

@ -9,7 +9,7 @@ use std::{self, mem, ops};
use std::ffi::CStr;
use ffi;
use pointer::PyObjectPtr;
use pointer::PyObject;
use python::{Python, ToPyPointer};
use err::PyResult;
use super::{PyTuple, PyType};
@ -102,10 +102,10 @@ exc_type!(UnicodeTranslateError, PyExc_UnicodeTranslateError);
impl UnicodeDecodeError {
pub fn new(py: Python, encoding: &CStr, input: &[u8],
range: ops::Range<usize>, reason: &CStr) -> PyResult<PyObjectPtr> {
range: ops::Range<usize>, reason: &CStr) -> PyResult<PyObject> {
unsafe {
let input: &[c_char] = mem::transmute(input);
PyObjectPtr::from_owned_ptr_or_err(
PyObject::from_owned_ptr_or_err(
py, ffi::PyUnicodeDecodeError_Create(
encoding.as_ptr(),
input.as_ptr(),
@ -117,7 +117,7 @@ impl UnicodeDecodeError {
}
pub fn new_utf8<'p>(py: Python, input: &[u8], err: std::str::Utf8Error)
-> PyResult<PyObjectPtr>
-> PyResult<PyObject>
{
let pos = err.valid_up_to();
UnicodeDecodeError::new(py, cstr!("utf-8"), input, pos .. pos+1, cstr!("invalid utf-8"))

View File

@ -5,7 +5,7 @@
use std::os::raw::c_double;
use ffi;
use pointer::PyObjectPtr;
use pointer::PyObject;
use python::{ToPyPointer, Python};
use err::PyErr;
use instance::{Py, PyObjectWithToken};
@ -17,7 +17,7 @@ use conversion::{ToPyObject, IntoPyObject};
/// by using [`ToPyObject`](trait.ToPyObject.html)
/// and [extract](struct.PyObject.html#method.extract)
/// with `f32`/`f64`.
pub struct PyFloat(PyObjectPtr);
pub struct PyFloat(PyObject);
pyobject_convert!(PyFloat);
pyobject_nativetype!(PyFloat, PyFloat_Type, PyFloat_Check);
@ -38,12 +38,12 @@ impl PyFloat {
}
impl ToPyObject for f64 {
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
PyFloat::new(py, *self).into()
}
}
impl IntoPyObject for f64 {
fn into_object(self, py: Python) -> PyObjectPtr {
fn into_object(self, py: Python) -> PyObject {
PyFloat::new(py, self).into()
}
}
@ -58,12 +58,12 @@ pyobject_extract!(py, obj to f64 => {
});
impl ToPyObject for f32 {
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
PyFloat::new(py, *self as f64).into()
}
}
impl IntoPyObject for f32 {
fn into_object(self, py: Python) -> PyObjectPtr {
fn into_object(self, py: Python) -> PyObject {
PyFloat::new(py, self as f64).into()
}
}

View File

@ -3,7 +3,7 @@
// based on Daniel Grunwald's https://github.com/dgrunwald/rust-cpython
use ffi;
use objects::PyObject;
use objects::PyInstance;
use python::{Python, ToPyPointer, IntoPyPointer};
use instance::PyObjectWithToken;
use err::{PyErr, PyResult, PyDowncastError};
@ -12,7 +12,7 @@ use err::{PyErr, PyResult, PyDowncastError};
///
/// Unlike other python objects, this class includes a `Python<'p>` token
/// so that `PyIterator` can implement the rust `Iterator` trait.
pub struct PyIterator<'p>(&'p PyObject);
pub struct PyIterator<'p>(&'p PyInstance);
impl <'p> PyIterator<'p> {
@ -34,7 +34,7 @@ impl <'p> PyIterator<'p> {
}
impl <'p> Iterator for PyIterator<'p> {
type Item = PyResult<&'p PyObject>;
type Item = PyResult<&'p PyInstance>;
/// Retrieves the next item from an iterator.
/// Returns `None` when the iterator is exhausted.
@ -64,7 +64,7 @@ mod tests {
use instance::AsPyRef;
use python::{Python, PyDowncastFrom};
use conversion::ToPyObject;
use objects::PyObject;
use objects::PyInstance;
use objectprotocol::ObjectProtocol;
#[test]
@ -72,7 +72,7 @@ mod tests {
let gil_guard = Python::acquire_gil();
let py = gil_guard.python();
let obj = vec![10, 20].to_object(py);
let inst = PyObject::downcast_from(obj.as_ref(py)).unwrap();
let inst = PyInstance::downcast_from(obj.as_ref(py)).unwrap();
let mut it = inst.iter().unwrap();
assert_eq!(10, it.next().unwrap().unwrap().extract().unwrap());
assert_eq!(20, it.next().unwrap().unwrap().extract().unwrap());

View File

@ -5,13 +5,13 @@
use err::{self, PyResult};
use ffi::{self, Py_ssize_t};
use instance::PyObjectWithToken;
use pointer::PyObjectPtr;
use objects::PyObject;
use pointer::PyObject;
use objects::PyInstance;
use python::{Python, ToPyPointer, IntoPyPointer};
use conversion::{ToPyObject, IntoPyObject};
/// Represents a Python `list`.
pub struct PyList(PyObjectPtr);
pub struct PyList(PyObject);
pyobject_convert!(PyList);
pyobject_nativetype!(PyList, PyList_Type, PyList_Check);
@ -48,10 +48,10 @@ impl PyList {
/// Gets the item at the specified index.
///
/// Panics if the index is out of range.
pub fn get_item(&self, index: isize) -> &PyObject {
pub fn get_item(&self, index: isize) -> &PyInstance {
unsafe {
let ptr = ffi::PyList_GetItem(self.as_ptr(), index as Py_ssize_t);
let ob = PyObjectPtr::from_borrowed_ptr(self.token(), ptr);
let ob = PyObject::from_borrowed_ptr(self.token(), ptr);
self.token().track_object(ob)
}
}
@ -59,10 +59,10 @@ impl PyList {
/// Gets the item at the specified index.
///
/// Panics if the index is out of range.
pub fn get_parked_item(&self, index: isize) -> PyObjectPtr {
pub fn get_parked_item(&self, index: isize) -> PyObject {
unsafe {
let ptr = ffi::PyList_GetItem(self.as_ptr(), index as Py_ssize_t);
PyObjectPtr::from_borrowed_ptr(self.token(), ptr)
PyObject::from_borrowed_ptr(self.token(), ptr)
}
}
@ -103,10 +103,10 @@ pub struct PyListIterator<'a> {
}
impl<'a> Iterator for PyListIterator<'a> {
type Item = &'a PyObject;
type Item = &'a PyInstance;
#[inline]
fn next(&mut self) -> Option<&'a PyObject> {
fn next(&mut self) -> Option<&'a PyInstance> {
if self.index < self.list.len() as isize {
let item = self.list.get_item(self.index);
self.index += 1;
@ -122,21 +122,21 @@ impl<'a> Iterator for PyListIterator<'a> {
impl <T> ToPyObject for [T] where T: ToPyObject {
fn to_object<'p>(&self, py: Python<'p>) -> PyObjectPtr {
fn to_object<'p>(&self, py: Python<'p>) -> PyObject {
unsafe {
let ptr = ffi::PyList_New(self.len() as Py_ssize_t);
for (i, e) in self.iter().enumerate() {
let obj = e.to_object(py).into_ptr();
ffi::PyList_SetItem(ptr, i as Py_ssize_t, obj);
}
PyObjectPtr::from_owned_ptr_or_panic(py, ptr)
PyObject::from_owned_ptr_or_panic(py, ptr)
}
}
}
impl <T> ToPyObject for Vec<T> where T: ToPyObject {
fn to_object<'p>(&self, py: Python<'p>) -> PyObjectPtr {
fn to_object<'p>(&self, py: Python<'p>) -> PyObject {
self.as_slice().to_object(py)
}
@ -144,14 +144,14 @@ impl <T> ToPyObject for Vec<T> where T: ToPyObject {
impl <T> IntoPyObject for Vec<T> where T: IntoPyObject {
fn into_object(self, py: Python) -> PyObjectPtr {
fn into_object(self, py: Python) -> PyObject {
unsafe {
let ptr = ffi::PyList_New(self.len() as Py_ssize_t);
for (i, e) in self.into_iter().enumerate() {
let obj = e.into_object(py).into_ptr();
ffi::PyList_SetItem(ptr, i as Py_ssize_t, obj);
}
PyObjectPtr::from_owned_ptr_or_panic(py, ptr)
PyObject::from_owned_ptr_or_panic(py, ptr)
}
}
}

View File

@ -33,7 +33,8 @@ macro_rules! pyobject_downcast(
($name: ident, $checkfunction: ident) => (
impl $crate::python::PyDowncastFrom for $name
{
fn downcast_from(ob: &$crate::PyObject) -> Result<&$name, $crate::PyDowncastError>
fn downcast_from(ob: &$crate::PyInstance)
-> Result<&$name, $crate::PyDowncastError>
{
use $crate::{ToPyPointer, PyObjectWithToken};
@ -46,11 +47,11 @@ macro_rules! pyobject_downcast(
}
}
unsafe fn unchecked_downcast_from(ob: &$crate::PyObject) -> &Self
unsafe fn unchecked_downcast_from(ob: &$crate::PyInstance) -> &Self
{
$crate::std::mem::transmute(ob)
}
unsafe fn unchecked_mut_downcast_from(ob: &$crate::PyObject) -> &mut Self
unsafe fn unchecked_mut_downcast_from(ob: &$crate::PyInstance) -> &mut Self
{
#[allow(mutable_transmutes)]
$crate::std::mem::transmute(ob)
@ -60,7 +61,7 @@ macro_rules! pyobject_downcast(
impl<'a> $crate::FromPyObject<'a> for &'a $name
{
/// Extracts `Self` from the source `PyObject`.
fn extract(ob: &'a $crate::PyObject) -> $crate::PyResult<Self>
fn extract(ob: &'a $crate::PyInstance) -> $crate::PyResult<Self>
{
use instance::PyObjectWithToken;
unsafe {
@ -77,7 +78,7 @@ macro_rules! pyobject_downcast(
macro_rules! pyobject_convert(
($name: ident) => (
impl<'a> $crate::std::convert::From<&'a $name> for &'a $crate::PyObject {
impl<'a> $crate::std::convert::From<&'a $name> for &'a $crate::PyInstance {
fn from(ob: &'a $name) -> Self {
unsafe{$crate::std::mem::transmute(ob)}
}
@ -89,8 +90,8 @@ macro_rules! pyobject_nativetype(
($name: ident) => {
impl $crate::PyNativeType for $name {}
impl $crate::std::convert::AsRef<$crate::PyObject> for $name {
fn as_ref(&self) -> &$crate::PyObject {
impl $crate::std::convert::AsRef<$crate::PyInstance> for $name {
fn as_ref(&self) -> &$crate::PyInstance {
unsafe{$crate::std::mem::transmute(self)}
}
}
@ -175,8 +176,8 @@ macro_rules! pyobject_nativetype(
impl $crate::ToPyObject for $name
{
#[inline]
fn to_object<'p>(&self, py: $crate::Python<'p>) -> $crate::PyObjectPtr {
unsafe {$crate::PyObjectPtr::from_borrowed_ptr(py, self.0.as_ptr())}
fn to_object<'p>(&self, py: $crate::Python<'p>) -> $crate::PyObject {
unsafe {$crate::PyObject::from_borrowed_ptr(py, self.0.as_ptr())}
}
#[inline]
@ -187,6 +188,14 @@ macro_rules! pyobject_nativetype(
}
}
impl<'a> $crate::IntoPyObject for &'a $name
{
#[inline]
fn into_object<'p>(self, py: $crate::Python) -> $crate::PyObject {
unsafe { $crate::PyObject::from_borrowed_ptr(py, self.as_ptr()) }
}
}
impl $crate::std::fmt::Debug for $name {
fn fmt(&self, f: &mut $crate::std::fmt::Formatter)
-> Result<(), $crate::std::fmt::Error>
@ -208,14 +217,14 @@ macro_rules! pyobject_nativetype(
}
pyobject_downcast!($name, $checkfunction);
};
};
);
macro_rules! pyobject_extract(
($py:ident, $obj:ident to $t:ty => $body: block) => {
impl<'source> $crate::FromPyObject<'source> for $t
{
fn extract($obj: &'source ::PyObject) -> $crate::PyResult<Self>
fn extract($obj: &'source $crate::PyInstance) -> $crate::PyResult<Self>
{
#[allow(unused_imports)]
use objectprotocol::ObjectProtocol;
@ -230,8 +239,8 @@ macro_rules! pyobject_extract(
use python::ToPyPointer;
/// Represents general python instance.
pub struct PyObject(::PyObjectPtr);
pyobject_nativetype!(PyObject, PyBaseObject_Type, PyObject_Check);
pub struct PyInstance(::PyObject);
pyobject_nativetype!(PyInstance, PyBaseObject_Type, PyObject_Check);
mod typeobject;
mod module;

View File

@ -8,16 +8,16 @@ use std::os::raw::c_char;
use std::ffi::{CStr, CString};
use conversion::{ToPyObject, IntoPyTuple};
use pointer::PyObjectPtr;
use pointer::PyObject;
use python::{Python, ToPyPointer};
use objects::{PyObject, PyDict, PyType, exc};
use objects::{PyInstance, PyDict, PyType, exc};
use objectprotocol::ObjectProtocol;
use instance::PyObjectWithToken;
use err::{PyResult, PyErr, ToPyErr};
/// Represents a Python module object.
pub struct PyModule(PyObjectPtr);
pub struct PyModule(PyObject);
pyobject_convert!(PyModule);
pyobject_nativetype!(PyModule, PyModule_Type, PyModule_Check);
@ -81,7 +81,7 @@ impl PyModule {
/// Calls a function in the module.
/// This is equivalent to the Python expression: `getattr(module, name)(*args, **kwargs)`
pub fn call<A>(&self, name: &str, args: A, kwargs: Option<&PyDict>) -> PyResult<&PyObject>
pub fn call<A>(&self, name: &str, args: A, kwargs: Option<&PyDict>) -> PyResult<&PyInstance>
where A: IntoPyTuple
{
self.getattr(name)?.call(args, kwargs)
@ -89,7 +89,7 @@ impl PyModule {
/// Gets a member from the module.
/// This is equivalent to the Python expression: `getattr(module, name)`
pub fn get(&self, name: &str) -> PyResult<&PyObject>
pub fn get(&self, name: &str) -> PyResult<&PyInstance>
{
self.getattr(name)
}

View File

@ -8,11 +8,11 @@ extern crate num_traits;
use self::num_traits::cast::cast;
use ffi;
use pointer::PyObjectPtr;
use pointer::PyObject;
use python::{ToPyPointer, IntoPyPointer, Python};
use err::{PyResult, PyErr};
use instance::{Py, PyObjectWithToken};
use objects::{exc, PyObject};
use objects::{exc, PyInstance};
use conversion::{ToPyObject, IntoPyObject, FromPyObject};
/// Represents a Python `int` object.
@ -23,7 +23,7 @@ use conversion::{ToPyObject, IntoPyObject, FromPyObject};
/// by using [ToPyObject](trait.ToPyObject.html)
/// and [extract](struct.PyObject.html#method.extract)
/// with the primitive Rust integer types.
pub struct PyInt(PyObjectPtr);
pub struct PyInt(PyObject);
pyobject_convert!(PyInt);
pyobject_nativetype!(PyInt, PyInt_Type, PyInt_Check);
@ -35,7 +35,7 @@ pyobject_nativetype!(PyInt, PyInt_Type, PyInt_Check);
/// by using [ToPyObject](trait.ToPyObject.html)
/// and [extract](struct.PyObject.html#method.extract)
/// with the primitive Rust integer types.
pub struct PyLong(PyObjectPtr);
pub struct PyLong(PyObject);
pyobject_convert!(PyLong);
pyobject_nativetype!(PyLong, PyLong_Type, PyLong_Check);
@ -66,16 +66,16 @@ impl PyInt {
macro_rules! int_fits_c_long(
($rust_type:ty) => (
impl ToPyObject for $rust_type {
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
unsafe {
PyObjectPtr::from_owned_ptr_or_panic(py, ffi::PyInt_FromLong(*self as c_long))
PyObject::from_owned_ptr_or_panic(py, ffi::PyInt_FromLong(*self as c_long))
}
}
}
impl IntoPyObject for $rust_type {
fn into_object(self, py: Python) -> PyObjectPtr {
fn into_object(self, py: Python) -> PyObject {
unsafe {
PyObjectPtr::from_owned_ptr_or_panic(py, ffi::PyInt_FromLong(self as c_long))
PyObject::from_owned_ptr_or_panic(py, ffi::PyInt_FromLong(self as c_long))
}
}
}
@ -97,12 +97,12 @@ macro_rules! int_fits_larger_int(
($rust_type:ty, $larger_type:ty) => (
impl ToPyObject for $rust_type {
#[inline]
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
(*self as $larger_type).to_object(py)
}
}
impl IntoPyObject for $rust_type {
fn into_object(self, py: Python) -> PyObjectPtr {
fn into_object(self, py: Python) -> PyObject {
(self as $larger_type).into_object(py)
}
}
@ -130,30 +130,30 @@ fn err_if_invalid_value<'p, T: PartialEq>
macro_rules! int_convert_u64_or_i64 (
($rust_type:ty, $pylong_from_ll_or_ull:expr, $pylong_as_ull_or_ull:expr) => (
impl ToPyObject for $rust_type {
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
unsafe {
let ptr = match cast::<$rust_type, c_long>(*self) {
Some(v) => ffi::PyInt_FromLong(v),
None => $pylong_from_ll_or_ull(*self)
};
PyObjectPtr::from_owned_ptr_or_panic(py, ptr)
PyObject::from_owned_ptr_or_panic(py, ptr)
}
}
}
impl IntoPyObject for $rust_type {
fn into_object(self, py: Python) -> PyObjectPtr {
fn into_object(self, py: Python) -> PyObject {
unsafe {
let ptr = match cast::<$rust_type, c_long>(self) {
Some(v) => ffi::PyInt_FromLong(v),
None => $pylong_from_ll_or_ull(self)
};
PyObjectPtr::from_owned_ptr_or_panic(py, ptr)
PyObject::from_owned_ptr_or_panic(py, ptr)
}
}
}
impl <'source> FromPyObject<'source> for $rust_type {
fn extract(obj: &'source PyObject) -> PyResult<$rust_type>
fn extract(obj: &'source PyInstance) -> PyResult<$rust_type>
{
let ptr = obj.as_ptr();
unsafe {
@ -165,7 +165,7 @@ macro_rules! int_convert_u64_or_i64 (
None => Err(overflow_error(obj.token()))
}
} else {
let num = PyObjectPtr::from_owned_ptr_or_err(
let num = PyObject::from_owned_ptr_or_err(
obj.token(), ffi::PyNumber_Long(ptr))?;
err_if_invalid_value(
obj.token(), !0, $pylong_as_ull_or_ull(num.into_ptr()))

View File

@ -8,10 +8,10 @@ extern crate num_traits;
use self::num_traits::cast::cast;
use ffi;
use pointer::PyObjectPtr;
use pointer::PyObject;
use python::{ToPyPointer, Python};
use err::{PyResult, PyErr};
use objects::{exc, PyObject};
use objects::{exc, PyInstance};
use instance::PyObjectWithToken;
use conversion::{ToPyObject, IntoPyObject, FromPyObject};
@ -21,7 +21,7 @@ use conversion::{ToPyObject, IntoPyObject, FromPyObject};
/// by using [`ToPyObject`](trait.ToPyObject.html)
/// and [extract](struct.PyObject.html#method.extract)
/// with the primitive Rust integer types.
pub struct PyLong(PyObjectPtr);
pub struct PyLong(PyObject);
pyobject_convert!(PyLong);
pyobject_nativetype!(PyLong, PyLong_Type, PyLong_Check);
@ -30,16 +30,16 @@ pyobject_nativetype!(PyLong, PyLong_Type, PyLong_Check);
macro_rules! int_fits_c_long(
($rust_type:ty) => (
impl ToPyObject for $rust_type {
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
unsafe {
PyObjectPtr::from_owned_ptr_or_panic(py, ffi::PyLong_FromLong(*self as c_long))
PyObject::from_owned_ptr_or_panic(py, ffi::PyLong_FromLong(*self as c_long))
}
}
}
impl IntoPyObject for $rust_type {
fn into_object(self, py: Python) -> PyObjectPtr {
fn into_object(self, py: Python) -> PyObject {
unsafe {
PyObjectPtr::from_owned_ptr_or_panic(py, ffi::PyLong_FromLong(self as c_long))
PyObject::from_owned_ptr_or_panic(py, ffi::PyLong_FromLong(self as c_long))
}
}
}
@ -61,12 +61,12 @@ macro_rules! int_fits_larger_int(
($rust_type:ty, $larger_type:ty) => (
impl ToPyObject for $rust_type {
#[inline]
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
(*self as $larger_type).to_object(py)
}
}
impl IntoPyObject for $rust_type {
fn into_object(self, py: Python) -> PyObjectPtr {
fn into_object(self, py: Python) -> PyObject {
(self as $larger_type).into_object(py)
}
}
@ -95,22 +95,22 @@ macro_rules! int_convert_u64_or_i64 (
($rust_type:ty, $pylong_from_ll_or_ull:expr, $pylong_as_ull_or_ull:expr) => (
impl ToPyObject for $rust_type {
#[inline]
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
unsafe {
PyObjectPtr::from_owned_ptr_or_panic(py, $pylong_from_ll_or_ull(*self))
PyObject::from_owned_ptr_or_panic(py, $pylong_from_ll_or_ull(*self))
}
}
}
impl IntoPyObject for $rust_type {
#[inline]
fn into_object(self, py: Python) -> PyObjectPtr {
fn into_object(self, py: Python) -> PyObject {
unsafe {
PyObjectPtr::from_owned_ptr_or_panic(py, $pylong_from_ll_or_ull(self))
PyObject::from_owned_ptr_or_panic(py, $pylong_from_ll_or_ull(self))
}
}
}
impl<'source> FromPyObject<'source> for $rust_type {
fn extract(ob: &'source PyObject) -> PyResult<$rust_type>
fn extract(ob: &'source PyInstance) -> PyResult<$rust_type>
{
let ptr = ob.as_ptr();
unsafe {

View File

@ -3,11 +3,11 @@
// based on Daniel Grunwald's https://github.com/dgrunwald/rust-cpython
use ffi;
use pointer::PyObjectPtr;
use pointer::PyObject;
use instance::PyObjectWithToken;
use python::{Python, ToPyPointer, PyDowncastFrom};
use conversion::{FromPyObject, ToPyObject};
use objects::{PyObject, PyList, PyTuple};
use objects::{PyInstance, PyList, PyTuple};
use ffi::Py_ssize_t;
use err;
use err::{PyErr, PyResult};
@ -16,7 +16,7 @@ use objectprotocol::ObjectProtocol;
/// Represents a reference to a python object supporting the sequence protocol.
pub struct PySequence(PyObjectPtr);
pub struct PySequence(PyObject);
pyobject_nativetype!(PySequence);
pyobject_downcast!(PySequence, PySequence_Check);
@ -84,7 +84,7 @@ impl PySequence {
/// Return the ith element of the Sequence. Equivalent to python `o[index]`
#[inline]
pub fn get_item(&self, index: isize) -> PyResult<&PyObject> {
pub fn get_item(&self, index: isize) -> PyResult<&PyInstance> {
unsafe {
self.token().cast_from_ptr_or_err(
ffi::PySequence_GetItem(self.as_ptr(), index as Py_ssize_t))
@ -94,7 +94,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<&PyObject> {
pub fn get_slice(&self, begin: isize, end: isize) -> PyResult<&PyInstance> {
unsafe {
self.token().cast_from_ptr_or_err(
ffi::PySequence_GetSlice(
@ -105,7 +105,7 @@ impl PySequence {
/// Assign object v to the ith element of o.
/// Equivalent to Python statement `o[i] = v`
#[inline]
pub fn set_item(&self, i: isize, v: &PyObject) -> PyResult<()> {
pub fn set_item(&self, i: isize, v: &PyInstance) -> PyResult<()> {
unsafe {
err::error_on_minusone(
self.token(),
@ -127,7 +127,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: &PyObject) -> PyResult<()> {
pub fn set_slice(&self, i1: isize, i2: isize, v: &PyInstance) -> PyResult<()> {
unsafe {
err::error_on_minusone(
self.token(), ffi::PySequence_SetSlice(
@ -210,7 +210,7 @@ impl PySequence {
impl<'a, T> FromPyObject<'a> for Vec<T> where T: FromPyObject<'a>
{
default fn extract(obj: &'a PyObject) -> PyResult<Self> {
default fn extract(obj: &'a PyInstance) -> PyResult<Self> {
extract_sequence(obj)
}
}
@ -219,7 +219,7 @@ impl<'a, T> FromPyObject<'a> for Vec<T> where T: FromPyObject<'a>
impl <'source, T> FromPyObject<'source> for Vec<T>
where for<'a> T: FromPyObject<'a> + buffer::Element + Copy
{
fn extract(py: Python, obj: &'source PyObject) -> PyResult<Self> {
fn extract(py: Python, obj: &'source PyInstance) -> PyResult<Self> {
// first try buffer protocol
if let Ok(buf) = buffer::PyBuffer::get(py, obj) {
if buf.dimensions() == 1 {
@ -235,7 +235,7 @@ impl <'source, T> FromPyObject<'source> for Vec<T>
}
}*/
fn extract_sequence<'s, T>(obj: &'s PyObject) -> PyResult<Vec<T>> where T: FromPyObject<'s>
fn extract_sequence<'s, T>(obj: &'s PyInstance) -> PyResult<Vec<T>> where T: FromPyObject<'s>
{
let seq = PySequence::downcast_from(obj)?;
let mut v = Vec::new();

View File

@ -4,17 +4,17 @@
use std::{hash, collections};
use ffi;
use python::{Python, ToPyPointer};
use pointer::PyObjectPtr;
use pointer::PyObject;
use conversion::ToPyObject;
use instance::{AsPyRef, Py, PyObjectWithToken};
use err::{self, PyResult, PyErr};
/// Represents a Python `set`
pub struct PySet(PyObjectPtr);
pub struct PySet(PyObject);
/// Represents a Python `frozenset`
pub struct PyFrozenSet(PyObjectPtr);
pub struct PyFrozenSet(PyObject);
pyobject_convert!(PySet);
pyobject_convert!(PyFrozenSet);
@ -72,9 +72,9 @@ impl PySet {
}
/// Remove and return an arbitrary element from the set
pub fn pop(&self) -> Option<PyObjectPtr> {
pub fn pop(&self) -> Option<PyObject> {
unsafe {
PyObjectPtr::from_owned_ptr_or_opt(self.token(), ffi::PySet_Pop(self.as_ptr()))
PyObject::from_owned_ptr_or_opt(self.token(), ffi::PySet_Pop(self.as_ptr()))
}
}
}
@ -82,7 +82,7 @@ impl PySet {
impl<T> ToPyObject for collections::HashSet<T>
where T: hash::Hash + Eq + ToPyObject
{
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
let set = PySet::new::<T>(py, &[]);
{
let s = set.as_ref(py);
@ -97,7 +97,7 @@ impl<T> ToPyObject for collections::HashSet<T>
impl<T> ToPyObject for collections::BTreeSet<T>
where T: hash::Hash + Eq + ToPyObject
{
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
let set = PySet::new::<T>(py, &[]);
{
let s = set.as_ref(py);

View File

@ -2,7 +2,7 @@
use std::os::raw::c_long;
use pointer::PyObjectPtr;
use pointer::PyObject;
use python::{ToPyPointer, Python};
use err::{PyErr, PyResult};
use ffi::{self, Py_ssize_t};
@ -11,7 +11,7 @@ use conversion::ToPyObject;
/// Represents a Python `slice`. Only `c_long` indeces supprted
/// at the moment by `PySlice` object.
pub struct PySlice(PyObjectPtr);
pub struct PySlice(PyObject);
pyobject_convert!(PySlice);
pyobject_nativetype!(PySlice, PySlice_Type, PySlice_Check);
@ -79,7 +79,7 @@ impl PySlice {
}
impl ToPyObject for PySliceIndices {
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
PySlice::new(py, self.start, self.stop, self.step).into()
}
}

View File

@ -9,14 +9,14 @@ use std::os::raw::c_char;
use ffi;
use instance::{Py, PyObjectWithToken};
use pointer::PyObjectPtr;
use objects::PyObject;
use pointer::PyObject;
use objects::PyInstance;
use python::{ToPyPointer, Python};
use err::{PyResult, PyErr};
use super::PyStringData;
/// Represents a Python string.
pub struct PyString(PyObjectPtr);
pub struct PyString(PyObject);
pyobject_convert!(PyString);
pyobject_nativetype!(PyString, PyUnicode_Type, PyUnicode_Check);
@ -26,7 +26,7 @@ pyobject_nativetype!(PyString, PyUnicode_Type, PyUnicode_Check);
pub use PyString as PyUnicode;
/// Represents a Python byte string.
pub struct PyBytes(PyObjectPtr);
pub struct PyBytes(PyObject);
pyobject_convert!(PyBytes);
pyobject_nativetype!(PyBytes, PyBytes_Type, PyBytes_Check);
@ -45,7 +45,7 @@ impl PyString {
}
}
pub fn from_object(py: Python, src: &PyObject, encoding: &str, errors: &str)
pub fn from_object(py: Python, src: &PyInstance, encoding: &str, errors: &str)
-> PyResult<Py<PyString>> {
unsafe {
Ok(Py::from_owned_ptr_or_err(

View File

@ -10,26 +10,26 @@ use std::os::raw::c_char;
use ffi;
use err::PyResult;
use pointer::PyObjectPtr;
use pointer::PyObject;
use instance::{Py, PyObjectWithToken};
use python::{Python, ToPyPointer};
use objectprotocol::ObjectProtocol;
use super::{PyObject, PyStringData};
use super::{PyInstance, PyStringData};
/// Represents a Python string.
pub struct PyString(PyObjectPtr);
pub struct PyString(PyObject);
pyobject_convert!(PyString);
pyobject_nativetype!(PyString, PyBaseString_Type, PyBaseString_Check);
/// Represents a Python unicode string.
pub struct PyUnicode(PyObjectPtr);
pub struct PyUnicode(PyObject);
pyobject_convert!(PyUnicode);
pyobject_nativetype!(PyUnicode, PyUnicode_Type, PyUnicode_Check);
/// Represents a Python byte string. Corresponds to `str` in Python 2
pub struct PyBytes(PyObjectPtr);
pub struct PyBytes(PyObject);
pyobject_convert!(PyBytes);
pyobject_nativetype!(PyBytes, PyBaseString_Type, PyString_Check);
@ -51,7 +51,7 @@ impl PyString {
}
}
pub fn from_object(src: &PyObject, encoding: &str, errors: &str) -> PyResult<Py<PyString>> {
pub fn from_object(src: &PyInstance, encoding: &str, errors: &str) -> PyResult<Py<PyString>> {
unsafe {
Ok(Py::from_owned_ptr_or_err(
src.token(), ffi::PyUnicode_FromEncodedObject(
@ -135,7 +135,7 @@ impl PyUnicode {
}
}
pub fn from_object(src: &PyObject, encoding: &str, errors: &str) -> PyResult<Py<PyUnicode>>
pub fn from_object(src: &PyInstance, encoding: &str, errors: &str) -> PyResult<Py<PyUnicode>>
{
unsafe {
Ok(Py::from_owned_ptr_or_err(

View File

@ -1,8 +1,8 @@
use std::borrow::Cow;
use err::PyResult;
use pointer::PyObjectPtr;
use objects::{PyObject, PyString};
use pointer::PyObject;
use objects::{PyInstance, PyString};
use objectprotocol::ObjectProtocol;
use python::Python;
use conversion::{ToPyObject, IntoPyObject, RefFromPyObject};
@ -11,13 +11,13 @@ use conversion::{ToPyObject, IntoPyObject, RefFromPyObject};
/// See `PyString::new` for details on the conversion.
impl ToPyObject for str {
#[inline]
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
PyString::new(py, self).into()
}
}
impl<'a> IntoPyObject for &'a str {
#[inline]
fn into_object(self, py: Python) -> PyObjectPtr {
fn into_object(self, py: Python) -> PyObject {
PyString::new(py, self).into()
}
}
@ -26,7 +26,7 @@ impl<'a> IntoPyObject for &'a str {
/// See `PyString::new` for details on the conversion.
impl<'a> ToPyObject for Cow<'a, str> {
#[inline]
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
PyString::new(py, self).into()
}
}
@ -35,19 +35,19 @@ impl<'a> ToPyObject for Cow<'a, str> {
/// See `PyString::new` for details on the conversion.
impl ToPyObject for String {
#[inline]
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
PyString::new(py, self).into()
}
}
impl IntoPyObject for String {
#[inline]
fn into_object(self, py: Python) -> PyObjectPtr {
fn into_object(self, py: Python) -> PyObject {
PyString::new(py, &self).into()
}
}
impl<'a> IntoPyObject for &'a String {
#[inline]
fn into_object(self, py: Python) -> PyObjectPtr {
fn into_object(self, py: Python) -> PyObject {
PyString::new(py, self).into()
}
}
@ -56,7 +56,7 @@ impl<'a> IntoPyObject for &'a String {
/// Accepts Python `str` and `unicode` objects.
impl<'source> ::FromPyObject<'source> for Cow<'source, str>
{
fn extract(ob: &'source PyObject) -> PyResult<Self>
fn extract(ob: &'source PyInstance) -> PyResult<Self>
{
try!(ob.cast_as::<PyString>()).to_string()
}
@ -70,7 +70,7 @@ pyobject_extract!(py, obj to String => {
});
impl RefFromPyObject for str {
fn with_extracted<F, R>(obj: &PyObject, f: F) -> PyResult<R>
fn with_extracted<F, R>(obj: &PyInstance, f: F) -> PyResult<R>
where F: FnOnce(&str) -> R
{
let s = try!(obj.extract::<Cow<str>>());

View File

@ -7,15 +7,15 @@ use std::slice;
use ffi::{self, Py_ssize_t};
use err::{PyErr, PyResult};
use instance::{Py, PyObjectWithToken};
use pointer::PyObjectPtr;
use objects::PyObject;
use pointer::PyObject;
use objects::PyInstance;
use objectprotocol::ObjectProtocol;
use python::{Python, ToPyPointer, IntoPyPointer};
use conversion::{FromPyObject, ToPyObject, IntoPyTuple, IntoPyObject};
use super::exc;
/// Represents a Python tuple object.
pub struct PyTuple(PyObjectPtr);
pub struct PyTuple(PyObject);
pyobject_convert!(PyTuple);
pyobject_nativetype!(PyTuple, PyTuple_Type, PyTuple_Check);
@ -54,7 +54,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) -> &PyObject {
pub fn get_item(&self, index: usize) -> &PyInstance {
// TODO: reconsider whether we should panic
// It's quite inconsistent that this method takes `Python` when `len()` does not.
assert!(index < self.len());
@ -65,13 +65,13 @@ impl PyTuple {
}
#[inline]
pub fn as_slice<'a>(&'a self) -> &'a [PyObjectPtr] {
pub fn as_slice<'a>(&'a self) -> &'a [PyObject] {
// This is safe because PyObject has the same memory layout as *mut ffi::PyObject,
// and because tuples are immutable.
// (We don't even need a Python token, thanks to immutability)
unsafe {
let ptr = self.as_ptr() as *mut ffi::PyTupleObject;
PyObjectPtr::borrow_from_owned_ptr_slice(
PyObject::borrow_from_owned_ptr_slice(
slice::from_raw_parts(
(*ptr).ob_item.as_ptr(), self.len()
))
@ -79,7 +79,7 @@ impl PyTuple {
}
#[inline]
pub fn iter(&self) -> slice::Iter<PyObjectPtr> {
pub fn iter(&self) -> slice::Iter<PyObject> {
self.as_slice().iter()
}
}
@ -115,20 +115,20 @@ fn wrong_tuple_length(py: Python, t: &PyTuple, expected_length: usize) -> PyErr
macro_rules! tuple_conversion ({$length:expr,$(($refN:ident, $n:tt, $T:ident)),+} => {
impl <$($T: ToPyObject),+> ToPyObject for ($($T,)+) {
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
unsafe {
let ptr = ffi::PyTuple_New($length);
$(ffi::PyTuple_SetItem(ptr, $n, self.$n.to_object(py).into_ptr());)+;
PyObjectPtr::from_owned_ptr_or_panic(py, ptr)
PyObject::from_owned_ptr_or_panic(py, ptr)
}
}
}
impl <$($T: IntoPyObject),+> IntoPyObject for ($($T,)+) {
fn into_object(self, py: Python) -> PyObjectPtr {
fn into_object(self, py: Python) -> PyObject {
unsafe {
let ptr = ffi::PyTuple_New($length);
$(ffi::PyTuple_SetItem(ptr, $n, self.$n.into_object(py).into_ptr());)+;
PyObjectPtr::from_owned_ptr_or_panic(py, ptr)
PyObject::from_owned_ptr_or_panic(py, ptr)
}
}
}
@ -144,7 +144,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 PyObject) -> PyResult<Self>
fn extract(obj: &'s PyInstance) -> PyResult<Self>
{
let t = try!(obj.cast_as::<PyTuple>());
let slice = t.as_slice();
@ -192,14 +192,14 @@ pub struct NoArgs;
/// Converts `NoArgs` to an empty Python tuple.
impl ToPyObject for NoArgs {
fn to_object(&self, py: Python) -> PyObjectPtr {
fn to_object(&self, py: Python) -> PyObject {
PyTuple::empty(py).into()
}
}
impl IntoPyObject for NoArgs
{
fn into_object(self, py: Python) -> PyObjectPtr {
fn into_object(self, py: Python) -> PyObject {
PyTuple::empty(py).into()
}
}
@ -239,7 +239,7 @@ mod test {
use instance::AsPyRef;
use python::{Python, PyDowncastFrom};
use conversion::ToPyObject;
use objects::PyObject;
use objects::PyInstance;
use objectprotocol::ObjectProtocol;
#[test]
@ -249,7 +249,7 @@ mod test {
let pyob = PyTuple::new(py, &[1, 2, 3]);
let ob = pyob.as_ref(py);
assert_eq!(3, ob.len());
let ob: &PyObject = ob.into();
let ob: &PyInstance = ob.into();
assert_eq!((1, 2, 3), ob.extract().unwrap());
}
@ -260,7 +260,7 @@ mod test {
let ob = (1, 2, 3).to_object(py);
let tuple = PyTuple::downcast_from(ob.as_ref(py)).unwrap();
assert_eq!(3, tuple.len());
let ob: &PyObject = tuple.into();
let ob: &PyInstance = tuple.into();
assert_eq!((1, 2, 3), ob.extract().unwrap());
}
}

View File

@ -6,14 +6,14 @@ use std::ffi::CStr;
use std::borrow::Cow;
use ffi;
use pointer::PyObjectPtr;
use pointer::PyObject;
use python::{Python, ToPyPointer};
use err::{PyErr, PyResult};
use instance::PyObjectWithToken;
use typeob::PyTypeObject;
/// Represents a reference to a Python type object.
pub struct PyType(PyObjectPtr);
pub struct PyType(PyObject);
pyobject_convert!(PyType);
pyobject_nativetype!(PyType, PyType_Type, PyType_Check);

View File

@ -4,41 +4,41 @@ use std;
use ffi;
use err::{PyErr, PyResult, PyDowncastError};
use instance::AsPyRef;
use objects::PyObject;
use conversion::{ToPyObject, IntoPyObject, FromPyObject};
use instance::{AsPyRef, PyObjectWithToken};
use objects::{PyInstance, PyDict};
use conversion::{ToPyObject, IntoPyObject, IntoPyTuple, FromPyObject};
use python::{Python, PyClone, ToPyPointer, IntoPyPointer};
/// Wrapper around unsafe `*mut ffi::PyObject` pointer. Decrement ref counter on `Drop`
#[derive(Debug)]
pub struct PyObjectPtr(*mut ffi::PyObject);
pub struct PyObject(*mut ffi::PyObject);
// `PyPtr` is thread-safe, because any python related operations require a Python<'p> token.
unsafe impl Send for PyObjectPtr {}
unsafe impl Sync for PyObjectPtr {}
unsafe impl Send for PyObject {}
unsafe impl Sync for PyObject {}
impl PyObjectPtr {
impl PyObject {
/// Creates a `PyPtr` instance for the given FFI pointer.
/// This moves ownership over the pointer into the `PyPtr`.
/// Undefined behavior if the pointer is NULL or invalid.
#[inline]
pub unsafe fn from_owned_ptr(_py: Python, ptr: *mut ffi::PyObject) -> PyObjectPtr {
pub unsafe fn from_owned_ptr(_py: Python, ptr: *mut ffi::PyObject) -> PyObject {
debug_assert!(!ptr.is_null() && ffi::Py_REFCNT(ptr) > 0,
format!("REFCNT: {:?} - {:?}", ptr, ffi::Py_REFCNT(ptr)));
PyObjectPtr(ptr)
PyObject(ptr)
}
/// Cast from ffi::PyObject ptr to a concrete object.
#[inline]
pub fn from_owned_ptr_or_panic(py: Python, ptr: *mut ffi::PyObject) -> PyObjectPtr
pub fn from_owned_ptr_or_panic(py: Python, ptr: *mut ffi::PyObject) -> PyObject
{
if ptr.is_null() {
::err::panic_after_error();
} else {
unsafe{
PyObjectPtr::from_owned_ptr(py, ptr)
PyObject::from_owned_ptr(py, ptr)
}
}
}
@ -47,13 +47,13 @@ impl PyObjectPtr {
/// returns a new reference (owned pointer).
/// Returns `Err(PyErr)` if the pointer is `null`.
/// Unsafe because the pointer might be invalid.
pub fn from_owned_ptr_or_err(py: Python, ptr: *mut ffi::PyObject) -> PyResult<PyObjectPtr>
pub fn from_owned_ptr_or_err(py: Python, ptr: *mut ffi::PyObject) -> PyResult<PyObject>
{
if ptr.is_null() {
Err(PyErr::fetch(py))
} else {
Ok(unsafe{
PyObjectPtr::from_owned_ptr(py, ptr)
PyObject::from_owned_ptr(py, ptr)
})
}
}
@ -62,13 +62,13 @@ impl PyObjectPtr {
/// returns a new reference (owned pointer).
/// Returns `None` if the pointer is `null`.
/// Unsafe because the pointer might be invalid.
pub fn from_owned_ptr_or_opt(py: Python, ptr: *mut ffi::PyObject) -> Option<PyObjectPtr>
pub fn from_owned_ptr_or_opt(py: Python, ptr: *mut ffi::PyObject) -> Option<PyObject>
{
if ptr.is_null() {
None
} else {
Some(unsafe{
PyObjectPtr::from_owned_ptr(py, ptr)
PyObject::from_owned_ptr(py, ptr)
})
}
}
@ -77,11 +77,11 @@ impl PyObjectPtr {
/// Calls Py_INCREF() on the ptr.
/// Undefined behavior if the pointer is NULL or invalid.
#[inline]
pub unsafe fn from_borrowed_ptr(_py: Python, ptr: *mut ffi::PyObject) -> PyObjectPtr {
pub unsafe fn from_borrowed_ptr(_py: Python, ptr: *mut ffi::PyObject) -> PyObject {
debug_assert!(!ptr.is_null() && ffi::Py_REFCNT(ptr) > 0,
format!("REFCNT: {:?} - {:?}", ptr, ffi::Py_REFCNT(ptr)));
ffi::Py_INCREF(ptr);
PyObjectPtr(ptr)
PyObject(ptr)
}
/// Creates a `PyPtr` instance for the given Python FFI pointer.
@ -90,12 +90,12 @@ impl PyObjectPtr {
/// Unsafe because the pointer might be invalid.
#[inline]
pub unsafe fn from_borrowed_ptr_or_err(py: Python, ptr: *mut ffi::PyObject)
-> PyResult<PyObjectPtr>
-> PyResult<PyObject>
{
if ptr.is_null() {
Err(PyErr::fetch(py))
} else {
Ok(PyObjectPtr::from_owned_ptr(py, ptr))
Ok(PyObject::from_owned_ptr(py, ptr))
}
}
@ -105,20 +105,20 @@ impl PyObjectPtr {
/// Unsafe because the pointer might be invalid.
#[inline]
pub unsafe fn from_borrowed_ptr_or_opt(py: Python, ptr: *mut ffi::PyObject)
-> Option<PyObjectPtr>
-> Option<PyObject>
{
if ptr.is_null() {
None
} else {
Some(PyObjectPtr::from_owned_ptr(py, ptr))
Some(PyObject::from_owned_ptr(py, ptr))
}
}
/// Transmutes a slice of owned FFI pointers to `&[Py<'p, PyObject>]`.
/// Transmutes a slice of owned FFI pointers to `&[PyObject]`.
/// Undefined behavior if any pointer in the slice is NULL or invalid.
#[inline]
pub unsafe fn borrow_from_owned_ptr_slice<'a>(ptr: &'a [*mut ffi::PyObject])
-> &'a [PyObjectPtr] {
-> &'a [PyObject] {
std::mem::transmute(ptr)
}
@ -152,6 +152,51 @@ impl PyObjectPtr {
FromPyObject::extract(self.as_ref(py))
}
/// Calls the object.
/// This is equivalent to the Python expression: 'self(*args, **kwargs)'
#[inline]
pub fn call<A>(&self, py: Python, args: A, kwargs: Option<&PyDict>) -> PyResult<PyObject>
where A: IntoPyTuple
{
let t = args.into_tuple(py);
let result = unsafe {
PyObject::from_borrowed_ptr_or_err(
py, ffi::PyObject_Call(self.as_ptr(), t.as_ptr(), kwargs.as_ptr()))
};
py.release(t);
result
}
/// Retrieves an attribute value.
/// This is equivalent to the Python expression 'self.attr_name'.
#[inline]
pub fn getattr<N>(&self, py: Python, attr_name: N) -> PyResult<PyObject>
where N: ToPyObject
{
attr_name.with_borrowed_ptr(py, |attr_name| unsafe {
PyObject::from_owned_ptr_or_err(
py, ffi::PyObject_GetAttr(self.as_ptr(), attr_name))
})
}
/// Calls a method on the object.
/// This is equivalent to the Python expression: 'self.name(*args, **kwargs)'
#[inline]
pub fn call_method<A>(&self, py: Python,
name: &str, args: A,
kwargs: Option<&PyDict>) -> PyResult<PyObject>
where A: IntoPyTuple
{
name.with_borrowed_ptr(py, |name| unsafe {
let t = args.into_tuple(py);
let ptr = ffi::PyObject_GetAttr(self.as_ptr(), name);
let result = PyObject::from_borrowed_ptr_or_err(
py, ffi::PyObject_Call(ptr, t.as_ptr(), kwargs.as_ptr()));
py.release(t);
result
})
}
/// Calls `ffi::Py_DECREF` and sets ptr to null value.
#[inline]
pub unsafe fn drop_ref(&mut self) {
@ -160,23 +205,23 @@ impl PyObjectPtr {
}
}
impl AsPyRef<PyObject> for PyObjectPtr {
impl AsPyRef<PyInstance> for PyObject {
#[inline]
fn as_ref(&self, _py: Python) -> &PyObject {
fn as_ref(&self, _py: Python) -> &PyInstance {
unsafe {std::mem::transmute(self)}
}
#[inline]
fn as_mut(&self, _py: Python) -> &mut PyObject {
unsafe {std::mem::transmute(self as *const _ as *mut PyObject)}
fn as_mut(&self, _py: Python) -> &mut PyInstance {
unsafe {std::mem::transmute(self as *const _ as *mut PyInstance)}
}
}
impl ToPyObject for PyObjectPtr
impl ToPyObject for PyObject
{
#[inline]
fn to_object<'p>(&self, py: Python<'p>) -> PyObjectPtr {
unsafe {PyObjectPtr::from_borrowed_ptr(py, self.as_ptr())}
fn to_object<'p>(&self, py: Python<'p>) -> PyObject {
unsafe {PyObject::from_borrowed_ptr(py, self.as_ptr())}
}
#[inline]
@ -187,7 +232,7 @@ impl ToPyObject for PyObjectPtr
}
}
impl ToPyPointer for PyObjectPtr {
impl ToPyPointer for PyObject {
/// Gets the underlying FFI pointer, returns a borrowed pointer.
#[inline]
fn as_ptr(&self) -> *mut ffi::PyObject {
@ -195,7 +240,7 @@ impl ToPyPointer for PyObjectPtr {
}
}
impl<'a> ToPyPointer for &'a PyObjectPtr {
impl<'a> ToPyPointer for &'a PyObject {
/// Gets the underlying FFI pointer, returns a borrowed pointer.
#[inline]
fn as_ptr(&self) -> *mut ffi::PyObject {
@ -203,7 +248,7 @@ impl<'a> ToPyPointer for &'a PyObjectPtr {
}
}
impl IntoPyPointer for PyObjectPtr {
impl IntoPyPointer for PyObject {
/// Gets the underlying FFI pointer, returns a owned pointer.
#[inline]
#[must_use]
@ -214,34 +259,46 @@ impl IntoPyPointer for PyObjectPtr {
}
}
impl PartialEq for PyObjectPtr {
impl PartialEq for PyObject {
#[inline]
fn eq(&self, o: &PyObjectPtr) -> bool {
fn eq(&self, o: &PyObject) -> bool {
self.0 == o.0
}
}
impl PyClone for PyObjectPtr {
impl PyClone for PyObject {
fn clone_ref(&self, py: Python) -> Self {
unsafe {
PyObjectPtr::from_borrowed_ptr(py, self.as_ptr())
PyObject::from_borrowed_ptr(py, self.as_ptr())
}
}
}
impl IntoPyObject for PyObjectPtr
impl IntoPyObject for PyObject
{
#[inline]
fn into_object(self, _py: Python) -> PyObjectPtr
fn into_object(self, _py: Python) -> PyObject
{
self
}
}
impl<'a> FromPyObject<'a> for PyObject
{
#[inline]
/// Extracts `Self` from the source `PyObject`.
fn extract(ob: &'a PyInstance) -> PyResult<Self>
{
unsafe {
Ok(PyObject::from_borrowed_ptr(ob.token(), ob.as_ptr()))
}
}
}
//use backtrace::Backtrace;
/// Dropping a `PyObject` instance decrements the reference count on the object by 1.
impl Drop for PyObjectPtr {
impl Drop for PyObject {
fn drop(&mut self) {
if !self.0.is_null() {

View File

@ -10,8 +10,8 @@ use std::os::raw::c_int;
use ffi;
use typeob::{PyTypeInfo, PyTypeObject, PyObjectAlloc};
use instance::{Py, PyToken};
use pointer::PyObjectPtr;
use objects::{PyObject, PyType, PyBool, PyDict, PyModule};
use pointer::PyObject;
use objects::{PyInstance, PyType, PyBool, PyDict, PyModule};
use err::{PyErr, PyResult, PyDowncastError, ToPyErr};
use pythonrun::{self, GILGuard};
@ -34,20 +34,20 @@ pub struct Python<'p>(PhantomData<&'p GILGuard>);
pub trait PyDowncastFrom : Sized {
/// Cast from PyObject to a concrete Python object type.
fn downcast_from(&PyObject) -> Result<&Self, PyDowncastError>;
fn downcast_from(&PyInstance) -> Result<&Self, PyDowncastError>;
/// Cast from PyObject to a concrete Python object type.
unsafe fn unchecked_downcast_from(&PyObject) -> &Self;
unsafe fn unchecked_downcast_from(&PyInstance) -> &Self;
/// Cast from PyObject to a concrete Python object type.
unsafe fn unchecked_mut_downcast_from(&PyObject) -> &mut Self;
unsafe fn unchecked_mut_downcast_from(&PyInstance) -> &mut Self;
}
/// Trait implemented by Python object types that allow a checked downcast.
pub trait PyMutDowncastFrom : Sized {
/// Cast from PyObject to a concrete Python object type.
fn downcast_mut_from(&mut PyObject) -> Result<&mut Self, PyDowncastError>;
fn downcast_mut_from(&mut PyInstance) -> Result<&mut Self, PyDowncastError>;
}
/// Trait implemented by Python object types that allow a checked downcast.
@ -155,7 +155,7 @@ impl<'p> Python<'p> {
/// If `globals` is `None`, it defaults to Python module `__main__`.
/// If `locals` is `None`, it defaults to the value of `globals`.
pub fn eval(self, code: &str, globals: Option<&PyDict>,
locals: Option<&PyDict>) -> PyResult<&'p PyObject> {
locals: Option<&PyDict>) -> PyResult<&'p PyInstance> {
self.run_code(code, ffi::Py_eval_input, globals, locals)
}
@ -176,7 +176,7 @@ impl<'p> Python<'p> {
/// If `globals` is `None`, it defaults to Python module `__main__`.
/// If `locals` is `None`, it defaults to the value of `globals`.
fn run_code(self, code: &str, start: c_int,
globals: Option<&PyDict>, locals: Option<&PyDict>) -> PyResult<&'p PyObject> {
globals: Option<&PyDict>, locals: Option<&PyDict>) -> PyResult<&'p PyInstance> {
let code = CString::new(code).map_err(|e| e.to_pyerr(self))?;
unsafe {
@ -209,8 +209,8 @@ impl<'p> Python<'p> {
/// Gets the Python builtin value `None`.
#[allow(non_snake_case)] // the Python keyword starts with uppercase
#[inline]
pub fn None(self) -> PyObjectPtr {
unsafe { PyObjectPtr::from_borrowed_ptr(self, ffi::Py_None()) }
pub fn None(self) -> PyObject {
unsafe { PyObject::from_borrowed_ptr(self, ffi::Py_None()) }
}
/// Gets the Python builtin value `True`.
@ -230,8 +230,8 @@ impl<'p> Python<'p> {
/// Gets the Python builtin value `NotImplemented`.
#[allow(non_snake_case)] // the Python keyword starts with uppercase
#[inline]
pub fn NotImplemented(self) -> PyObjectPtr {
unsafe { PyObjectPtr::from_borrowed_ptr(self, ffi::Py_NotImplemented()) }
pub fn NotImplemented(self) -> PyObject {
unsafe { PyObject::from_borrowed_ptr(self, ffi::Py_NotImplemented()) }
}
/// Create new python object and move T instance under python management
@ -277,7 +277,7 @@ impl<'p> Python<'p> {
impl<'p> Python<'p> {
pub fn checked_cast_as<D>(self, obj: PyObjectPtr) -> Result<&'p D, PyDowncastError<'p>>
pub fn checked_cast_as<D>(self, obj: PyObject) -> Result<&'p D, PyDowncastError<'p>>
where D: PyDowncastFrom
{
unsafe {
@ -286,7 +286,7 @@ impl<'p> Python<'p> {
}
}
pub unsafe fn cast_as<D>(self, obj: PyObjectPtr) -> &'p D
pub unsafe fn cast_as<D>(self, obj: PyObject) -> &'p D
where D: PyDowncastFrom
{
let p = pythonrun::register(self, obj);
@ -296,7 +296,7 @@ impl<'p> Python<'p> {
pub unsafe fn cast_from_ptr<D>(self, ptr: *mut ffi::PyObject) -> &'p D
where D: PyDowncastFrom
{
let obj = PyObjectPtr::from_owned_ptr_or_panic(self, ptr);
let obj = PyObject::from_owned_ptr_or_panic(self, ptr);
let p = pythonrun::register(self, obj);
<D as PyDowncastFrom>::unchecked_downcast_from(p)
}
@ -304,7 +304,7 @@ impl<'p> Python<'p> {
pub fn cast_from_ptr_or_err<D>(self, ptr: *mut ffi::PyObject) -> PyResult<&'p D>
where D: PyDowncastFrom
{
let obj = PyObjectPtr::from_owned_ptr_or_err(self, ptr)?;
let obj = PyObject::from_owned_ptr_or_err(self, ptr)?;
unsafe {
let p = pythonrun::register(self, obj);
Ok(<D as PyDowncastFrom>::unchecked_downcast_from(p))
@ -318,7 +318,7 @@ impl<'p> Python<'p> {
None
} else {
unsafe {
let obj = PyObjectPtr::from_owned_ptr(self, ptr);
let obj = PyObject::from_owned_ptr(self, ptr);
let p = pythonrun::register(self, obj);
Some(<D as PyDowncastFrom>::unchecked_downcast_from(p))
}
@ -328,7 +328,7 @@ impl<'p> Python<'p> {
pub unsafe fn cast_from_borrowed_ptr<D>(self, ptr: *mut ffi::PyObject) -> &'p D
where D: PyDowncastFrom
{
let obj = PyObjectPtr::from_borrowed_ptr(self, ptr);
let obj = PyObject::from_borrowed_ptr(self, ptr);
let p = pythonrun::register(self, obj);
<D as PyDowncastFrom>::unchecked_downcast_from(p)
}
@ -337,7 +337,7 @@ impl<'p> Python<'p> {
-> PyResult<&'p D>
where D: PyDowncastFrom
{
let obj = PyObjectPtr::from_borrowed_ptr_or_err(self, ptr)?;
let obj = PyObject::from_borrowed_ptr_or_err(self, ptr)?;
let p = pythonrun::register(self, obj);
Ok(<D as PyDowncastFrom>::unchecked_downcast_from(p))
}
@ -349,7 +349,7 @@ impl<'p> Python<'p> {
if ptr.is_null() {
None
} else {
let obj = PyObjectPtr::from_borrowed_ptr(self, ptr);
let obj = PyObject::from_borrowed_ptr(self, ptr);
let p = pythonrun::register(self, obj);
Some(<D as PyDowncastFrom>::unchecked_downcast_from(p))
}
@ -358,12 +358,12 @@ impl<'p> Python<'p> {
pub unsafe fn mut_cast_from_borrowed_ptr<D>(self, ptr: *mut ffi::PyObject) -> &'p mut D
where D: PyDowncastFrom
{
let obj = PyObjectPtr::from_borrowed_ptr(self, ptr);
let obj = PyObject::from_borrowed_ptr(self, ptr);
let p = pythonrun::register(self, obj);
<D as PyDowncastFrom>::unchecked_mut_downcast_from(p)
}
pub fn track_object(self, obj: PyObjectPtr) -> &'p PyObject
pub fn track_object(self, obj: PyObject) -> &'p PyInstance
{
unsafe { pythonrun::register(self, obj) }
}
@ -373,7 +373,7 @@ impl<'p> Python<'p> {
mod test {
use Python;
use objectprotocol::ObjectProtocol;
use objects::{PyObject, PyBool, PyList, PyInt, PyDict};
use objects::{PyInstance, PyBool, PyList, PyInt, PyDict};
#[test]
fn test_eval() {
@ -405,7 +405,7 @@ mod test {
fn test_is_instance() {
let gil = Python::acquire_gil();
let py = gil.python();
assert!(py.is_instance::<PyBool, PyObject>(py.True().into()).unwrap());
assert!(py.is_instance::<PyBool, PyInstance>(py.True().into()).unwrap());
let list = PyList::new(py, &[1, 2, 3, 4]);
assert!(!py.is_instance::<PyBool, _>(list.as_ref()).unwrap());
assert!(py.is_instance::<PyList, _>(list.as_ref()).unwrap());

View File

@ -5,8 +5,8 @@
use std::{sync, rc, marker, mem};
use ffi;
use python::{Python, ToPyPointer};
use pointer::PyObjectPtr;
use objects::PyObject;
use pointer::PyObject;
use objects::PyInstance;
static START: sync::Once = sync::ONCE_INIT;
@ -96,7 +96,7 @@ impl Drop for GILGuard {
}
}
static mut POOL: *mut Vec<PyObjectPtr> = 0 as *mut _;
static mut POOL: *mut Vec<PyObject> = 0 as *mut _;
pub struct Pool {
pos: usize,
@ -106,7 +106,7 @@ pub struct Pool {
impl Pool {
#[inline]
pub unsafe fn new() -> Pool {
let pool: &'static mut Vec<PyObject> = mem::transmute(POOL);
let pool: &'static mut Vec<PyInstance> = mem::transmute(POOL);
Pool{ pos: pool.len(), no_send: marker::PhantomData }
}
// /// Retrieves the marker type that proves that the GIL was acquired.
@ -124,14 +124,14 @@ impl Drop for Pool {
}
}
pub unsafe fn register<'p>(_py: Python<'p>, obj: PyObjectPtr) -> &'p PyObject {
let pool: &'static mut Vec<PyObjectPtr> = mem::transmute(POOL);
pub unsafe fn register<'p>(_py: Python<'p>, obj: PyObject) -> &'p PyInstance {
let pool: &'static mut Vec<PyObject> = mem::transmute(POOL);
pool.push(obj);
mem::transmute(&pool[pool.len()-1])
}
pub unsafe fn drain(pos: usize) {
let pool: &'static mut Vec<PyObjectPtr> = mem::transmute(POOL);
let pool: &'static mut Vec<PyObject> = mem::transmute(POOL);
let len = pool.len();
if pos < len {
@ -153,7 +153,7 @@ impl GILGuard {
unsafe {
let gstate = ffi::PyGILState_Ensure(); // acquire GIL
let pool: &'static mut Vec<PyObject> = mem::transmute(POOL);
let pool: &'static mut Vec<PyInstance> = mem::transmute(POOL);
GILGuard { pos: pool.len(), gstate: gstate, no_send: marker::PhantomData }
}

View File

@ -382,7 +382,7 @@ fn static_method_with_args() {
#[py::class]
struct GCIntegration {
self_ref: RefCell<PyObjectPtr>,
self_ref: RefCell<PyObject>,
dropped: TestDropCall,
token: PyToken,
}
@ -489,11 +489,11 @@ impl<'p> PyObjectProtocol<'p> for StringMethods {
Ok(format!("format({})", format_spec))
}
fn __unicode__(&self) -> PyResult<PyObjectPtr> {
fn __unicode__(&self) -> PyResult<PyObject> {
Ok(PyString::new(self.token(), "unicode").into())
}
fn __bytes__(&self) -> PyResult<PyObjectPtr> {
fn __bytes__(&self) -> PyResult<PyObject> {
Ok(PyBytes::new(self.token(), b"bytes").into())
}
}
@ -791,35 +791,35 @@ impl PyObjectProtocol for BinaryArithmetic {
#[py::proto]
impl PyNumberProtocol for BinaryArithmetic {
fn __add__(&self, rhs: &PyObject) -> PyResult<String> {
fn __add__(&self, rhs: &PyInstance) -> PyResult<String> {
Ok(format!("{:?} + {:?}", self, rhs))
}
fn __sub__(&self, rhs: &PyObject) -> PyResult<String> {
fn __sub__(&self, rhs: &PyInstance) -> PyResult<String> {
Ok(format!("{:?} - {:?}", self, rhs))
}
fn __mul__(&self, rhs: &PyObject) -> PyResult<String> {
fn __mul__(&self, rhs: &PyInstance) -> PyResult<String> {
Ok(format!("{:?} * {:?}", self, rhs))
}
fn __lshift__(&self, rhs: &PyObject) -> PyResult<String> {
fn __lshift__(&self, rhs: &PyInstance) -> PyResult<String> {
Ok(format!("{:?} << {:?}", self, rhs))
}
fn __rshift__(&self, rhs: &PyObject) -> PyResult<String> {
fn __rshift__(&self, rhs: &PyInstance) -> PyResult<String> {
Ok(format!("{:?} >> {:?}", self, rhs))
}
fn __and__(&self, rhs: &PyObject) -> PyResult<String> {
fn __and__(&self, rhs: &PyInstance) -> PyResult<String> {
Ok(format!("{:?} & {:?}", self, rhs))
}
fn __xor__(&self, rhs: &PyObject) -> PyResult<String> {
fn __xor__(&self, rhs: &PyInstance) -> PyResult<String> {
Ok(format!("{:?} ^ {:?}", self, rhs))
}
fn __or__(&self, rhs: &PyObject) -> PyResult<String> {
fn __or__(&self, rhs: &PyInstance) -> PyResult<String> {
Ok(format!("{:?} | {:?}", self, rhs))
}
}
@ -862,7 +862,7 @@ impl PyObjectProtocol for RichComparisons {
Ok("RC")
}
fn __richcmp__(&self, other: &PyObject, op: CompareOp) -> PyResult<String> {
fn __richcmp__(&self, other: &PyInstance, op: CompareOp) -> PyResult<String> {
match op {
CompareOp::Lt => Ok(format!("{} < {:?}", self.__repr__().unwrap(), other)),
CompareOp::Le => Ok(format!("{} <= {:?}", self.__repr__().unwrap(), other)),
@ -885,7 +885,7 @@ impl PyObjectProtocol for RichComparisons2 {
Ok("RC2")
}
fn __richcmp__(&self, other: &'p PyObject, op: CompareOp) -> PyResult<PyObjectPtr> {
fn __richcmp__(&self, other: &'p PyInstance, op: CompareOp) -> PyResult<PyObject> {
match op {
CompareOp::Eq => Ok(true.to_object(self.token())),
CompareOp::Ne => Ok(false.to_object(self.token())),
@ -1048,8 +1048,8 @@ impl<'p> PyContextProtocol<'p> for ContextManager {
fn __exit__(&mut self,
ty: Option<&'p PyType>,
value: Option<&'p PyObject>,
traceback: Option<&'p PyObject>) -> PyResult<bool> {
value: Option<&'p PyInstance>,
traceback: Option<&'p PyInstance>) -> PyResult<bool> {
self.exit_called = true;
if ty == Some(self.token().get_type::<exc::ValueError>()) {
Ok(true)

View File

@ -28,7 +28,7 @@ struct Test {
#[py::proto]
impl<'p> PyMappingProtocol<'p> for Test
{
fn __getitem__(&self, idx: &PyObject) -> PyResult<PyObjectPtr> {
fn __getitem__(&self, idx: &PyInstance) -> PyResult<PyObject> {
if let Ok(slice) = idx.cast_as::<PySlice>() {
let indices = slice.indices(1000)?;
if indices.start == 100 && indices.stop == 200 && indices.step == 1 {