remove Token

This commit is contained in:
Nikolay Kim 2017-05-28 08:57:34 -07:00
parent 6c87c9b77b
commit 969cba2c16
36 changed files with 458 additions and 356 deletions

View File

@ -54,36 +54,32 @@ fn impl_class(cls: &syn::Ident, base: &syn::Ident, token: Option<syn::Ident>) ->
let extra = if let Some(token) = token {
Some(quote! {
impl _pyo3::python::PythonObjectWithToken for #cls {
fn token<'p>(&'p self) -> _pyo3::python::Token<'p> {
self.#token.token()
fn token<'p>(&'p self) -> _pyo3::python::Python<'p> {
self.#token.token()
}
}
/*impl std::fmt::Debug for #cls {
impl std::fmt::Debug for #cls {
fn fmt(&self, f : &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
self.token().with(|py| {
let ptr = <#cls as _pyo3::python::ToPythonPointer>::as_ptr(self);
let repr = unsafe {
_pyo3::Py::<_pyo3::PyString>::cast_from_owned_nullptr(
py, _pyo3::ffi::PyObject_Repr(ptr))
.map_err(|_| std::fmt::Error)? };
f.write_str(&repr.to_string_lossy())
})
let ptr = <#cls as _pyo3::python::ToPythonPointer>::as_ptr(self);
let repr = unsafe {
_pyo3::Py::<_pyo3::PyString>::cast_from_owned_nullptr(
self.token(), _pyo3::ffi::PyObject_Repr(ptr))
.map_err(|_| std::fmt::Error)? };
f.write_str(&repr.to_string_lossy())
}
}
impl std::fmt::Display for #cls {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
self.token().with(|py| {
let ptr = <#cls as _pyo3::python::ToPythonPointer>::as_ptr(self);
let s = unsafe {
_pyo3::Py::<_pyo3::PyString>::cast_from_owned_nullptr(
py, _pyo3::ffi::PyObject_Str(ptr)
).map_err(|_| std::fmt::Error)?};
f.write_str(&s.to_string_lossy())
})
let ptr = <#cls as _pyo3::python::ToPythonPointer>::as_ptr(self);
let s = unsafe {
_pyo3::Py::<_pyo3::PyString>::cast_from_owned_nullptr(
self.token(), _pyo3::ffi::PyObject_Str(ptr)
).map_err(|_| std::fmt::Error)?};
f.write_str(&s.to_string_lossy())
}
}*/
}
})
} else {
None

View File

@ -48,10 +48,10 @@ pub fn impl_wrap(cls: &Box<syn::Ty>, name: &syn::Ident, spec: &FnSpec) -> Tokens
{
const LOCATION: &'static str = concat!(stringify!(#cls),".",stringify!(#name),"()");
_pyo3::callback::cb_meth(LOCATION, |py| {
let mut slf: Py<#cls> = Py::from_borrowed_ptr(py.token(), slf);
let mut slf: Py<#cls> = Py::from_borrowed_ptr(py, slf);
let args: _pyo3::Py<_pyo3::PyTuple> =
_pyo3::Py::from_borrowed_ptr(py.token(), args);
_pyo3::Py::from_borrowed_ptr(py, args);
let kwargs: Option<_pyo3::Py<_pyo3::PyDict>> =
_pyo3::argparse::get_kwargs(py, kwargs);
@ -78,10 +78,10 @@ pub fn impl_proto_wrap(cls: &Box<syn::Ty>, name: &syn::Ident, spec: &FnSpec) ->
{
const LOCATION: &'static str = concat!(stringify!(#cls),".",stringify!(#name),"()");
_pyo3::callback::cb_meth(LOCATION, |py| {
let mut slf: Py<#cls> = Py::from_borrowed_ptr(py.token(), slf);
let mut slf: Py<#cls> = Py::from_borrowed_ptr(py, slf);
let args: _pyo3::Py<_pyo3::PyTuple> =
_pyo3::Py::from_borrowed_ptr(py.token(), args);
_pyo3::Py::from_borrowed_ptr(py, args);
let kwargs: Option<_pyo3::Py<_pyo3::PyDict>> =
_pyo3::argparse::get_kwargs(py, kwargs);
@ -111,9 +111,9 @@ pub fn impl_wrap_new(cls: &Box<syn::Ty>, name: &syn::Ident, spec: &FnSpec) -> To
_pyo3::callback::cb_meth(LOCATION, |py| {
let cls: _pyo3::Py<_pyo3::PyType> = _pyo3::Py::from_borrowed_ptr(
py.token(), cls as *mut _pyo3::ffi::PyObject);
py, cls as *mut _pyo3::ffi::PyObject);
let args: _pyo3::Py<_pyo3::PyTuple> =
_pyo3::Py::from_borrowed_ptr(py.token(), args);
_pyo3::Py::from_borrowed_ptr(py, args);
let kwargs: Option<_pyo3::Py<_pyo3::PyDict>> =
_pyo3::argparse::get_kwargs(py, kwargs);
@ -161,8 +161,8 @@ fn impl_wrap_setter(cls: &Box<syn::Ty>, name: &syn::Ident, spec: &FnSpec) -> Tok
const LOCATION: &'static str = concat!(
stringify!(#cls), ".setter", stringify!(#name), "()");
_pyo3::callback::cb_setter(LOCATION, |py| {
let mut slf = _pyo3::Py::<#cls>::from_borrowed_ptr(py.token(), slf);
let value = _pyo3::PyObject::from_borrowed_ptr(py.token(), value);
let mut slf = _pyo3::Py::<#cls>::from_borrowed_ptr(py, slf);
let value = _pyo3::PyObject::from_borrowed_ptr(py, value);
let result = match <#val_ty as _pyo3::FromPyObject>::extract(&value) {
Ok(val) => slf.#name(py, val),

View File

@ -54,7 +54,7 @@ pub fn parse_args<'p>(py: Python<'p>,
let nkeywords = kwargs.map_or(0, |d| d.len());
if !accept_args && (nargs + nkeywords > params.len()) {
return Err(err::PyErr::new::<exc::TypeError, _>(
py.token(),
py,
format!("{}{} takes at most {} argument{} ({} given)",
fname.unwrap_or("function"),
if fname.is_some() { "()" } else { "" },
@ -72,7 +72,7 @@ pub fn parse_args<'p>(py: Python<'p>,
used_keywords += 1;
if i < nargs {
return Err(err::PyErr::new::<exc::TypeError, _>(
py.token(),
py,
format!("Argument given by name ('{}') and position ({})",
p.name, i+1)));
}
@ -84,7 +84,7 @@ pub fn parse_args<'p>(py: Python<'p>,
*out = None;
if !p.is_optional {
return Err(err::PyErr::new::<exc::TypeError, _>(
py.token(),
py,
format!("Required argument ('{}') (pos {}) not found",
p.name, i+1)));
}
@ -98,7 +98,7 @@ pub fn parse_args<'p>(py: Python<'p>,
let key = try!(try!(key.cast_as::<PyString>()).to_string());
if !params.iter().any(|p| p.name == key) {
return Err(err::PyErr::new::<exc::TypeError, _>(
py.token(),
py,
format!("'{}' is an invalid keyword argument for this function",
key)));
}
@ -360,7 +360,7 @@ pub unsafe fn get_kwargs<'p>(py: Python<'p>, ptr: *mut ffi::PyObject) -> Option<
if ptr.is_null() {
None
} else {
Some(Py::<PyDict>::from_borrowed_ptr(py.token(), ptr))
Some(Py::<PyDict>::from_borrowed_ptr(py, ptr))
}
}

View File

@ -401,7 +401,7 @@ impl PyBuffer {
return incompatible_format_error(py);
}
unsafe {
err::error_on_minusone(py.token(), ffi::PyBuffer_ToContiguous(
err::error_on_minusone(py, ffi::PyBuffer_ToContiguous(
target.as_ptr() as *mut raw::c_void,
&*self.0 as *const ffi::Py_buffer as *mut ffi::Py_buffer,
self.0.len,
@ -436,7 +436,7 @@ impl PyBuffer {
unsafe {
// Copy the buffer into the uninitialized space in the vector.
// Due to T:Copy, we don't need to be concerned with Drop impls.
err::error_on_minusone(py.token(), ffi::PyBuffer_ToContiguous(
err::error_on_minusone(py, ffi::PyBuffer_ToContiguous(
vec.as_mut_ptr() as *mut raw::c_void,
&*self.0 as *const ffi::Py_buffer as *mut ffi::Py_buffer,
self.0.len,
@ -487,7 +487,7 @@ impl PyBuffer {
return incompatible_format_error(py);
}
unsafe {
err::error_on_minusone(py.token(), ffi::PyBuffer_FromContiguous(
err::error_on_minusone(py, ffi::PyBuffer_FromContiguous(
&*self.0 as *const ffi::Py_buffer as *mut ffi::Py_buffer,
source.as_ptr() as *mut raw::c_void,
self.0.len,
@ -499,17 +499,17 @@ impl PyBuffer {
fn slice_length_error(py: Python) -> PyResult<()> {
Err(err::PyErr::new::<exc::BufferError, _>(
py.token(), "Slice length does not match buffer length."))
py, "Slice length does not match buffer length."))
}
fn incompatible_format_error(py: Python) -> PyResult<()> {
Err(err::PyErr::new::<exc::BufferError, _>(
py.token(), "Slice type is incompatible with buffer format."))
py, "Slice type is incompatible with buffer format."))
}
fn buffer_readonly_error(py: Python) -> PyResult<()> {
Err(err::PyErr::new::<exc::BufferError, _>(
py.token(), "Cannot write to read-only buffer."))
py, "Cannot write to read-only buffer."))
}
impl Drop for PyBuffer {

View File

@ -5,7 +5,7 @@ use std::{any, mem, ptr, isize, io, panic};
use libc;
use pyptr::Py;
use python::{Python, IntoPythonPointer, PythonObjectWithToken};
use python::{Python, IntoPythonPointer};
use objects::exc;
use conversion::IntoPyObject;
use ffi::{self, Py_hash_t};
@ -27,7 +27,7 @@ impl<S> CallbackConverter<S> for PyObjectCallbackConverter
type R = *mut ffi::PyObject;
fn convert(val: S, py: Python) -> *mut ffi::PyObject {
val.into_object(py.token()).into_ptr()
val.into_object(py).into_ptr()
}
#[inline]
@ -63,7 +63,7 @@ impl CallbackConverter<usize> for LenResultConverter {
val as isize
} else {
PyErr::new_lazy_init(
py.get_type::<exc::OverflowError>(), None).restore(py.token());
py.get_type::<exc::OverflowError>(), None).restore(py);
-1
}
}
@ -177,7 +177,7 @@ pub unsafe fn handle<'p, F, T, C>(location: &str, _c: C, f: F) -> C::R
C::convert(val, py)
}
Err(e) => {
e.restore(py.token());
e.restore(py);
C::error_value()
}
}
@ -204,14 +204,14 @@ pub unsafe fn cb_unary<Slf, F, T, C>(location: &str,
let guard = AbortOnDrop(location);
let ret = panic::catch_unwind(|| {
let py = Python::assume_gil_acquired();
let mut slf: Py<Slf> = Py::from_borrowed_ptr(py.token(), slf);
let mut slf: Py<Slf> = Py::from_borrowed_ptr(py, slf);
match f(py, slf.as_mut()) {
Ok(val) => {
C::convert(val, py)
}
Err(e) => {
e.restore(py.token());
e.restore(py);
C::error_value()
}
}
@ -236,7 +236,7 @@ pub unsafe fn cb_unary_unit<Slf, F>(location: &str, slf: *mut ffi::PyObject, f:
let guard = AbortOnDrop(location);
let ret = panic::catch_unwind(|| {
let py = Python::assume_gil_acquired();
let mut slf: Py<Slf> = Py::from_borrowed_ptr(py.token(), slf);
let mut slf: Py<Slf> = Py::from_borrowed_ptr(py, slf);
f(py, slf.as_mut())
});
@ -298,7 +298,7 @@ pub unsafe fn cb_convert<C, T>(_c: C, py: Python, value: PyResult<T>) -> C::R
match value {
Ok(val) => C::convert(val, py),
Err(e) => {
e.restore(py.token());
e.restore(py);
C::error_value()
}
}

View File

@ -8,7 +8,7 @@
use ffi;
use err::PyResult;
use python::{Python, PythonObjectWithToken};
use python::Python;
use callback::PyObjectCallbackConverter;
use typeob::PyTypeInfo;
use class::methods::PyMethodDef;

View File

@ -11,7 +11,7 @@ use std::os::raw::c_int;
use ::{Py, CompareOp};
use ffi;
use err::{PyErr, PyResult};
use python::{Python, IntoPythonPointer, PythonObjectWithToken};
use python::{Python, IntoPythonPointer};
use objects::{exc, PyObject};
use typeob::PyTypeInfo;
use conversion::{ToPyObject, FromPyObject, IntoPyObject};
@ -345,8 +345,8 @@ impl<T> PyObjectRichcmpProtocolImpl for T where T: for<'p> PyObjectRichcmpProtoc
let guard = ::callback::AbortOnDrop(LOCATION);
let ret = std::panic::catch_unwind(|| {
let py = Python::assume_gil_acquired();
let slf = Py::<T>::from_borrowed_ptr(py.token(), slf);
let arg = PyObject::from_borrowed_ptr(py.token(), arg);
let slf = Py::<T>::from_borrowed_ptr(py, slf);
let arg = PyObject::from_borrowed_ptr(py, arg);
let res = match extract_op(py, op) {
Ok(op) => {
@ -361,10 +361,10 @@ impl<T> PyObjectRichcmpProtocolImpl for T where T: for<'p> PyObjectRichcmpProtoc
};
match res {
Ok(val) => {
val.into_object(py.token()).into_ptr()
val.into_object(py).into_ptr()
}
Err(e) => {
e.restore(py.token());
e.restore(py);
std::ptr::null_mut()
}
}
@ -396,6 +396,6 @@ fn extract_op(py: Python, op: c_int) -> PyResult<CompareOp> {
_ => Err(PyErr::new_lazy_init(
py.get_type::<exc::ValueError>(),
Some("tp_richcompare called with invalid comparison operator"
.to_object(py.token()))))
.to_object(py))))
}
}

View File

@ -9,7 +9,7 @@ use std::os::raw::c_int;
use ffi;
use err::PyResult;
use python::{Python, PythonObjectWithToken};
use python::Python;
use objects::PyObject;
use typeob::PyTypeInfo;
use callback::{handle, UnitCallbackConverter};
@ -73,7 +73,7 @@ impl ffi::PyBufferProcs {
{
const LOCATION: &'static str = concat!(stringify!(T), ".buffer_get::<PyBufferProtocol>()");
handle(LOCATION, UnitCallbackConverter, |py| {
let slf = PyObject::from_borrowed_ptr(py.token(), slf);
let slf = PyObject::from_borrowed_ptr(py, slf);
slf.bf_getbuffer(py, arg1, arg2)
})
}

View File

@ -9,7 +9,7 @@ use std::os::raw::c_int;
use ffi;
use err::PyResult;
use python::{Python, PythonObjectWithToken};
use python::Python;
use objects::{PyObject, PyType};
use callback::{PyObjectCallbackConverter, UnitCallbackConverter};
use typeob::PyTypeInfo;

View File

@ -8,7 +8,7 @@ use std::os::raw::{c_int, c_void};
use ffi;
use pyptr::Py;
use python::{Python, ToPythonPointer, PythonObjectWithToken};
use python::{Python, ToPythonPointer};
use callback::AbortOnDrop;
use class::NO_METHODS;
use typeob::PyTypeInfo;
@ -90,7 +90,7 @@ unsafe extern "C" fn tp_traverse<T>(slf: *mut ffi::PyObject,
let guard = AbortOnDrop(LOCATION);
let py = Python::assume_gil_acquired();
let visit = PyVisit { visit: visit, arg: arg, _py: py };
let slf: Py<T> = Py::from_borrowed_ptr(py.token(), slf);
let slf: Py<T> = Py::from_borrowed_ptr(py, slf);
let ret = match T::__traverse__(&slf, py, visit) {
Ok(()) => 0,
@ -107,7 +107,7 @@ unsafe extern "C" fn tp_clear<T>(slf: *mut ffi::PyObject) -> c_int
let guard = AbortOnDrop(LOCATION);
let py = Python::assume_gil_acquired();
let slf: Py<T> = Py::from_borrowed_ptr(py.token(), slf);
let slf: Py<T> = Py::from_borrowed_ptr(py, slf);
T::__clear__(slf.as_mut(), py);
mem::forget(guard);
0

View File

@ -8,7 +8,7 @@
use ffi;
use err::PyResult;
use python::{Python, PythonObjectWithToken};
use python::Python;
use typeob::PyTypeInfo;
use callback::PyObjectCallbackConverter;

View File

@ -16,7 +16,7 @@ macro_rules! py_unary_func {
let guard = $crate::callback::AbortOnDrop(LOCATION);
let ret = $crate::std::panic::catch_unwind(|| {
let py = $crate::Python::assume_gil_acquired();
let mut slf = $crate::Py::<T>::from_borrowed_ptr(py.token(), slf);
let mut slf = $crate::Py::<T>::from_borrowed_ptr(py, slf);
let res = slf.as_mut().$f(py).into();
match res {
@ -25,7 +25,7 @@ macro_rules! py_unary_func {
::convert(val, py)
}
Err(e) => {
e.restore(py.token());
e.restore(py);
<$conv as $crate::callback::CallbackConverter<$res_type>>
::error_value()
}
@ -60,7 +60,7 @@ macro_rules! py_unary_func_self {
let guard = $crate::callback::AbortOnDrop(LOCATION);
let ret = $crate::std::panic::catch_unwind(|| {
let py = $crate::Python::assume_gil_acquired();
let mut slf = $crate::Py::<T>::from_borrowed_ptr(py.token(), slf);
let mut slf = $crate::Py::<T>::from_borrowed_ptr(py, slf);
let res = slf.$f(py).into();
match res {
@ -69,7 +69,7 @@ macro_rules! py_unary_func_self {
::convert(val, py)
}
Err(e) => {
e.restore(py.token());
e.restore(py);
<$conv as $crate::callback::CallbackConverter<$res_type>>
::error_value()
}
@ -126,8 +126,8 @@ macro_rules! py_binary_func{
let guard = $crate::callback::AbortOnDrop(LOCATION);
let ret = $crate::std::panic::catch_unwind(|| {
let py = $crate::Python::assume_gil_acquired();
let mut slf = $crate::Py::<T>::from_borrowed_ptr(py.token(), slf);
let arg = $crate::PyObject::from_borrowed_ptr(py.token(), arg);
let mut slf = $crate::Py::<T>::from_borrowed_ptr(py, slf);
let arg = $crate::PyObject::from_borrowed_ptr(py, arg);
let result = match arg.extract() {
Ok(arg) => {
@ -142,7 +142,7 @@ macro_rules! py_binary_func{
::convert(val, py)
}
Err(e) => {
e.restore(py.token());
e.restore(py);
<$conv as $crate::callback::CallbackConverter<$res_type>>
::error_value()
}
@ -178,8 +178,8 @@ macro_rules! py_binary_self_func{
let guard = $crate::callback::AbortOnDrop(LOCATION);
let ret = $crate::std::panic::catch_unwind(|| {
let py = $crate::Python::assume_gil_acquired();
let mut slf1 = $crate::Py::<T>::from_borrowed_ptr(py.token(), slf);
let arg = $crate::PyObject::from_borrowed_ptr(py.token(), arg);
let mut slf1 = $crate::Py::<T>::from_borrowed_ptr(py, slf);
let arg = $crate::PyObject::from_borrowed_ptr(py, arg);
let result = match arg.extract() {
Ok(arg) => {
@ -193,7 +193,7 @@ macro_rules! py_binary_self_func{
slf
}
Err(e) => {
e.restore(py.token());
e.restore(py);
$crate::std::ptr::null_mut()
}
}
@ -228,7 +228,7 @@ macro_rules! py_ssizearg_func {
let guard = $crate::callback::AbortOnDrop(LOCATION);
let ret = $crate::std::panic::catch_unwind(|| {
let py = $crate::Python::assume_gil_acquired();
let mut slf = $crate::Py::<T>::from_borrowed_ptr(py.token(), slf);
let mut slf = $crate::Py::<T>::from_borrowed_ptr(py, slf);
let result = slf.as_mut().$f(py, arg as isize).into();
match result {
@ -237,7 +237,7 @@ macro_rules! py_ssizearg_func {
::convert(val, py)
}
Err(e) => {
e.restore(py.token());
e.restore(py);
<$conv as $crate::callback::CallbackConverter<$res_type>>
::error_value()
}
@ -276,9 +276,9 @@ macro_rules! py_ternary_func{
let guard = $crate::callback::AbortOnDrop(LOCATION);
let ret = $crate::std::panic::catch_unwind(|| {
let py = $crate::Python::assume_gil_acquired();
let mut slf = $crate::Py::<T>::from_borrowed_ptr(py.token(), slf);
let arg1 = $crate::PyObject::from_borrowed_ptr(py.token(), arg1);
let arg2 = $crate::PyObject::from_borrowed_ptr(py.token(), arg2);
let mut slf = $crate::Py::<T>::from_borrowed_ptr(py, slf);
let arg1 = $crate::PyObject::from_borrowed_ptr(py, arg1);
let arg2 = $crate::PyObject::from_borrowed_ptr(py, arg2);
let result = match arg1.extract() {
Ok(arg1) => match arg2.extract() {
@ -294,7 +294,7 @@ macro_rules! py_ternary_func{
::convert(val, py)
}
Err(e) => {
e.restore(py.token());
e.restore(py);
<$conv as $crate::callback::CallbackConverter<$res_type>>
::error_value()
}
@ -333,9 +333,9 @@ macro_rules! py_ternary_self_func{
let guard = $crate::callback::AbortOnDrop(LOCATION);
let ret = $crate::std::panic::catch_unwind(|| {
let py = $crate::Python::assume_gil_acquired();
let mut slf1 = $crate::Py::<T>::from_borrowed_ptr(py.token(), slf);
let arg1 = $crate::PyObject::from_borrowed_ptr(py.token(), arg1);
let arg2 = $crate::PyObject::from_borrowed_ptr(py.token(), arg2);
let mut slf1 = $crate::Py::<T>::from_borrowed_ptr(py, slf);
let arg1 = $crate::PyObject::from_borrowed_ptr(py, arg1);
let arg2 = $crate::PyObject::from_borrowed_ptr(py, arg2);
let result = match arg1.extract() {
Ok(arg1) => match arg2.extract() {
@ -348,7 +348,7 @@ macro_rules! py_ternary_self_func{
match result {
Ok(_) => slf,
Err(e) => {
e.restore(py.token());
e.restore(py);
$crate::std::ptr::null_mut()
}
}
@ -385,13 +385,13 @@ macro_rules! py_func_set{
$crate::callback::cb_unary_unit::<T, _>(LOCATION, slf, |py, slf| {
if value.is_null() {
let e = PyErr::new::<exc::NotImplementedError, _>(
py.token(), format!("Subscript deletion not supported by {:?}",
py, format!("Subscript deletion not supported by {:?}",
stringify!(T)));
e.restore(py.token());
e.restore(py);
return -1
} else {
let name = ::PyObject::from_borrowed_ptr(py.token(), name);
let value = ::PyObject::from_borrowed_ptr(py.token(), value);
let name = ::PyObject::from_borrowed_ptr(py, name);
let value = ::PyObject::from_borrowed_ptr(py, value);
let result = match name.extract() {
Ok(name) => match value.extract() {
Ok(value) => {
@ -405,7 +405,7 @@ macro_rules! py_func_set{
Ok(_) =>
0,
Err(e) => {
e.restore(py.token());
e.restore(py);
-1
}
}
@ -432,10 +432,10 @@ macro_rules! py_func_del{
let guard = $crate::callback::AbortOnDrop(LOCATION);
let ret = $crate::std::panic::catch_unwind(|| {
let py = $crate::Python::assume_gil_acquired();
let mut slf = $crate::Py::<T>::from_borrowed_ptr(py.token(), slf);
let mut slf = $crate::Py::<T>::from_borrowed_ptr(py, slf);
if value.is_null() {
let name = PyObject::from_borrowed_ptr(py.token(), name);
let name = PyObject::from_borrowed_ptr(py, name);
let result = match name.extract() {
Ok(name) =>
slf.as_mut().$f(py, name).into(),
@ -445,15 +445,15 @@ macro_rules! py_func_del{
Ok(_) =>
0,
Err(e) => {
e.restore(py.token());
e.restore(py);
-1
}
}
} else {
let e = PyErr::new::<exc::NotImplementedError, _>(
py.token(), format!("Subscript assignment not supported by {:?}",
py, format!("Subscript assignment not supported by {:?}",
stringify!(T)));
e.restore(py.token());
e.restore(py);
return -1
}
@ -490,8 +490,8 @@ macro_rules! py_func_set_del{
let guard = $crate::callback::AbortOnDrop(LOCATION);
let ret = $crate::std::panic::catch_unwind(|| {
let py = $crate::Python::assume_gil_acquired();
let mut slf = $crate::Py::<T>::from_borrowed_ptr(py.token(), slf);
let name = PyObject::from_borrowed_ptr(py.token(), name);
let mut slf = $crate::Py::<T>::from_borrowed_ptr(py, slf);
let name = PyObject::from_borrowed_ptr(py, name);
if value.is_null() {
let result = match name.extract() {
@ -503,12 +503,12 @@ macro_rules! py_func_set_del{
Ok(_) =>
0,
Err(e) => {
e.restore(py.token());
e.restore(py);
-1
}
}
} else {
let value = ::PyObject::from_borrowed_ptr(py.token(), value);
let value = ::PyObject::from_borrowed_ptr(py, value);
let result = match name.extract() {
Ok(name) => match value.extract() {
Ok(value) => {
@ -522,7 +522,7 @@ macro_rules! py_func_set_del{
Ok(_) =>
0,
Err(e) => {
e.restore(py.token());
e.restore(py);
-1
}
}

View File

@ -5,7 +5,7 @@
use ffi;
use err::{PyErr, PyResult};
use python::{Python, PythonObjectWithToken};
use python::Python;
use objects::{exc, PyObject};
use callback::{PyObjectCallbackConverter, LenResultConverter};
use conversion::{ToPyObject, FromPyObject};

View File

@ -5,7 +5,7 @@
use ffi;
use err::PyResult;
use python::{Python, PythonObjectWithToken};
use python::Python;
use callback::PyObjectCallbackConverter;
use typeob::PyTypeInfo;
use class::methods::PyMethodDef;
@ -135,7 +135,7 @@ pub trait PyNumberSubProtocol<'p>: PyNumberProtocol<'p> {
}
pub trait PyNumberMulProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>;
type Success: ToPyObject;
type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>;
}
pub trait PyNumberMatmulProtocol<'p>: PyNumberProtocol<'p> {
@ -931,7 +931,7 @@ impl<'p, T> PyNumberNegProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_negative() -> Option<ffi::unaryfunc> {None}
}
impl<T> PyNumberNegProtocolImpl for T
where T: for<'p> PyNumberNegProtocol<'p> + ToPyObject + IntoPyObject
where T: for<'p> PyNumberNegProtocol<'p>
{
#[inline]
fn nb_negative() -> Option<ffi::unaryfunc> {
@ -946,7 +946,7 @@ impl<'p, T> PyNumberPosProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_positive() -> Option<ffi::unaryfunc> {None}
}
impl<T> PyNumberPosProtocolImpl for T
where T: for<'p> PyNumberPosProtocol<'p> + ToPyObject + IntoPyObject
where T: for<'p> PyNumberPosProtocol<'p>
{
fn nb_positive() -> Option<ffi::unaryfunc> {
py_unary_func!(PyNumberPosProtocol, T::__pos__, T::Success, PyObjectCallbackConverter)
@ -960,7 +960,7 @@ impl<'p, T> PyNumberAbsProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_absolute() -> Option<ffi::unaryfunc> {None}
}
impl<T> PyNumberAbsProtocolImpl for T
where T: for<'p> PyNumberAbsProtocol<'p> + ToPyObject + IntoPyObject
where T: for<'p> PyNumberAbsProtocol<'p>
{
fn nb_absolute() -> Option<ffi::unaryfunc> {
py_unary_func!(PyNumberAbsProtocol, T::__abs__, T::Success, PyObjectCallbackConverter)
@ -974,7 +974,7 @@ impl<'p, T> PyNumberInvertProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_invert() -> Option<ffi::unaryfunc> {None}
}
impl<T> PyNumberInvertProtocolImpl for T
where T: for<'p> PyNumberInvertProtocol<'p> + ToPyObject + IntoPyObject
where T: for<'p> PyNumberInvertProtocol<'p>
{
fn nb_invert() -> Option<ffi::unaryfunc> {
py_unary_func!(PyNumberInvertProtocol, T::__invert__,
@ -989,7 +989,7 @@ impl<'p, T> PyNumberIntProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_int() -> Option<ffi::unaryfunc> {None}
}
impl<T> PyNumberIntProtocolImpl for T
where T: for<'p> PyNumberIntProtocol<'p> + ToPyObject + IntoPyObject
where T: for<'p> PyNumberIntProtocol<'p>
{
fn nb_int() -> Option<ffi::unaryfunc> {
py_unary_func!(PyNumberIntProtocol, T::__int__,
@ -1003,8 +1003,8 @@ trait PyNumberFloatProtocolImpl {
impl<'p, T> PyNumberFloatProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_float() -> Option<ffi::unaryfunc> {None}
}
impl<T> PyNumberFloatProtocolImpl for T
where T: for<'p> PyNumberFloatProtocol<'p> + ToPyObject + IntoPyObject {
impl<T> PyNumberFloatProtocolImpl for T where T: for<'p> PyNumberFloatProtocol<'p>
{
fn nb_float() -> Option<ffi::unaryfunc> {
py_unary_func!(PyNumberFloatProtocol, T::__float__,
T::Success, PyObjectCallbackConverter)

View File

@ -6,7 +6,7 @@
use std::os::raw::c_int;
use ffi;
use python::{Python, PythonObjectWithToken};
use python::Python;
use err::{PyErr, PyResult};
use objects::{exc, PyObject};
use callback::{PyObjectCallbackConverter, LenResultConverter, BoolCallbackConverter};
@ -195,12 +195,12 @@ impl<T> PySequenceSetItemProtocolImpl for T where T: for<'p> PySequenceSetItemPr
::callback::cb_unary_unit::<T, _>(LOCATION, slf, |py, slf| {
if value.is_null() {
let e = PyErr::new::<exc::NotImplementedError, _>(
py.token(),
py,
format!("Item deletion not supported by {:?}", stringify!(T)));
e.restore(py.token());
e.restore(py);
return -1
} else {
let value = PyObject::from_borrowed_ptr(py.token(), value);
let value = PyObject::from_borrowed_ptr(py, value);
let result = match value.extract() {
Ok(value) => {
slf.__setitem__(py, key as isize, value).into()
@ -210,7 +210,7 @@ impl<T> PySequenceSetItemProtocolImpl for T where T: for<'p> PySequenceSetItemPr
match result {
Ok(_) => 0,
Err(e) => {
e.restore(py.token());
e.restore(py);
-1
}
}
@ -248,15 +248,15 @@ impl<T> PySequenceDelItemProtocolImpl for T where T: for<'p> PySequenceDelItemPr
match result {
Ok(_) => 0,
Err(e) => {
e.restore(py.token());
e.restore(py);
-1
}
}
} else {
let e = PyErr::new::<exc::NotImplementedError, _>(
py.token(), format!("Item assignment not supported by {:?}",
py, format!("Item assignment not supported by {:?}",
stringify!(T)));
e.restore(py.token());
e.restore(py);
return -1
}
})
@ -282,12 +282,12 @@ impl<T> PySequenceDelItemProtocolImpl for T
match result {
Ok(_) => 0,
Err(e) => {
e.restore(py.token());
e.restore(py);
-1
}
}
} else {
let value = ::PyObject::from_borrowed_ptr(py.token(), value);
let value = ::PyObject::from_borrowed_ptr(py, value);
let result = match value.extract() {
Ok(value) => {
slf.__setitem__(py, key as isize, value).into()
@ -297,7 +297,7 @@ impl<T> PySequenceDelItemProtocolImpl for T
match result {
Ok(_) => 0,
Err(e) => {
e.restore(py.token());
e.restore(py);
-1
}
}

View File

@ -1,7 +1,7 @@
use ffi;
use err::PyResult;
use pyptr::{Py, PyPtr};
use python::{Python, ToPythonPointer, Token};
use python::{Python, ToPythonPointer};
use objects::{PyObject, PyTuple};
use typeob::{PyTypeInfo};
@ -10,7 +10,7 @@ use typeob::{PyTypeInfo};
pub trait ToPyObject {
/// Converts self into a Python object.
fn to_object(&self, py: Token) -> PyPtr<PyObject>;
fn to_object<'p>(&self, py: Python<'p>) -> PyPtr<PyObject>;
/// Converts self into a Python object and calls the specified closure
/// on the native FFI pointer underlying the Python object.
@ -18,7 +18,7 @@ pub trait ToPyObject {
/// May be more efficient than `to_py_object` because it does not need
/// to touch any reference counts when the input object already is a Python object.
#[inline]
fn with_borrowed_ptr<F, R>(&self, py: Token, f: F) -> R
fn with_borrowed_ptr<F, R>(&self, py: Python, f: F) -> R
where F: FnOnce(*mut ffi::PyObject) -> R
{
let obj = self.to_object(py).into_object();
@ -30,7 +30,7 @@ pub trait IntoPyObject {
/// Converts self into a Python object. (Consumes self)
#[inline]
fn into_object(self, py: Token) -> PyPtr<PyObject>
fn into_object(self, py: Python) -> PyPtr<PyObject>
where Self: Sized;
}
@ -39,12 +39,12 @@ pub trait IntoPyObject {
pub trait ToPyTuple {
/// Converts self into a PyTuple object.
fn to_py_tuple(&self, py: Token) -> PyPtr<PyTuple>;
fn to_py_tuple<'p>(&self, py: Python<'p>) -> PyPtr<PyTuple>;
/// Converts self into a PyTuple object and calls the specified closure
/// on the native FFI pointer underlying the Python object.
#[inline]
fn with_borrowed_ptr<F, R>(&self, py: Token, f: F) -> R
fn with_borrowed_ptr<F, R>(&self, py: Python, f: F) -> R
where F: FnOnce(*mut ffi::PyObject) -> R
{
let obj = self.to_py_tuple(py);
@ -102,7 +102,7 @@ impl <'p, T: ?Sized> RefFromPyObject<'p> for T
impl<T> IntoPyObject for T where T: ToPyObject
{
#[inline]
default fn into_object(self, py: Token) -> PyPtr<PyObject> where Self: Sized
default fn into_object(self, py: Python) -> PyPtr<PyObject> where Self: Sized
{
self.to_object(py)
}
@ -114,12 +114,12 @@ impl<T> IntoPyObject for T where T: ToPyObject
impl <'a, T: ?Sized> ToPyObject for &'a T where T: ToPyObject {
#[inline]
default fn to_object(&self, py: Token) -> PyPtr<PyObject> {
default fn to_object(&self, py: Python) -> PyPtr<PyObject> {
<T as ToPyObject>::to_object(*self, py)
}
#[inline]
fn with_borrowed_ptr<F, R>(&self, py: Token, f: F) -> R
fn with_borrowed_ptr<F, R>(&self, py: Python, f: F) -> R
where F: FnOnce(*mut ffi::PyObject) -> R
{
<T as ToPyObject>::with_borrowed_ptr(*self, py, f)
@ -130,7 +130,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: Token) -> PyPtr<PyObject> {
fn to_object(&self, py: Python) -> PyPtr<PyObject> {
match *self {
Some(ref val) => val.to_object(py),
None => py.None()
@ -140,7 +140,7 @@ impl <T> ToPyObject for Option<T> where T: ToPyObject {
impl<T> IntoPyObject for Option<T> where T: IntoPyObject {
fn into_object(self, py: Token) -> PyPtr<PyObject> {
fn into_object(self, py: Python) -> PyPtr<PyObject> {
match self {
Some(val) => val.into_object(py),
None => py.None()
@ -151,7 +151,7 @@ impl<T> IntoPyObject for Option<T> where T: IntoPyObject {
/// `()` is converted to Python `None`.
impl ToPyObject for () {
fn to_object(&self, py: Token) -> PyPtr<PyObject> {
fn to_object(&self, py: Python) -> PyPtr<PyObject> {
py.None()
}
}

View File

@ -4,7 +4,7 @@ use libc;
use ffi;
use pyptr::{Py, PyPtr};
use python::{ToPythonPointer, Python, IntoPythonPointer, Token, PythonObjectWithToken};
use python::{ToPythonPointer, IntoPythonPointer, Python};
use objects::{PyObject, PyType, exc};
use typeob::{PyTypeObject};
use conversion::{ToPyObject, ToPyTuple};
@ -102,7 +102,7 @@ pub type PyResult<T> = Result<T, PyErr>;
// Marker type that indicates an error while downcasting
pub struct PyDowncastError<'p>(pub Token<'p>, pub Option<&'p str>);
pub struct PyDowncastError<'p>(pub Python<'p>, pub Option<&'p str>);
impl PyErr {
@ -117,7 +117,7 @@ impl PyErr {
///
/// Example:
/// `return Err(PyErr::new::<exc::TypeError, _>(py, "Error message"));`
pub fn new<T, V>(py: Token, value: V) -> PyErr
pub fn new<T, V>(py: Python, value: V) -> PyErr
where T: PyTypeObject, V: ToPyObject
{
PyErr::new_helper(py, py.get_type::<T>(), value.to_object(py))
@ -125,7 +125,7 @@ impl PyErr {
/// Gets whether an error is present in the Python interpreter's global state.
#[inline]
pub fn occurred(_ : Token) -> bool {
pub fn occurred(_ : Python) -> bool {
unsafe { !ffi::PyErr_Occurred().is_null() }
}
@ -157,7 +157,7 @@ impl PyErr {
/// Retrieves the current error from the Python interpreter's global state.
/// The error is cleared from the Python interpreter.
/// If no error is set, returns a `SystemError`.
pub fn fetch(py: Token) -> PyErr {
pub fn fetch(py: Python) -> PyErr {
unsafe {
let mut ptype : *mut ffi::PyObject = std::mem::uninitialized();
let mut pvalue : *mut ffi::PyObject = std::mem::uninitialized();
@ -167,7 +167,7 @@ impl PyErr {
}
}
unsafe fn new_from_ffi_tuple(py: Token,
unsafe fn new_from_ffi_tuple(py: Python,
ptype: *mut ffi::PyObject,
pvalue: *mut ffi::PyObject,
ptraceback: *mut ffi::PyObject) -> PyErr {
@ -184,7 +184,7 @@ impl PyErr {
}
}
fn new_helper(_py: Token, ty: PyPtr<PyType>, value: PyPtr<PyObject>) -> PyErr {
fn new_helper(_py: Python, ty: PyPtr<PyType>, value: PyPtr<PyObject>) -> PyErr {
assert!(unsafe { ffi::PyExceptionClass_Check(ty.as_ptr()) } != 0);
PyErr {
ptype: ty,
@ -198,11 +198,11 @@ impl PyErr {
/// `obj` must be an Python exception instance, the PyErr will use that instance.
/// 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<O>(py: Token, obj: O) -> PyErr where O: ToPyObject {
pub fn from_instance<O>(py: Python, obj: O) -> PyErr where O: ToPyObject {
PyErr::from_instance_helper(py, obj.to_object(py))
}
fn from_instance_helper<'p>(py: Token, obj: PyPtr<PyObject>) -> PyErr {
fn from_instance_helper<'p>(py: Python, obj: PyPtr<PyObject>) -> PyErr {
if unsafe { ffi::PyExceptionInstance_Check(obj.as_ptr()) } != 0 {
PyErr {
ptype: unsafe { PyPtr::<PyType>::from_borrowed_ptr(
@ -241,7 +241,7 @@ impl PyErr {
/// `exc` is the exception type; usually one of the standard exceptions like `py.get_type::<exc::RuntimeError>()`.
/// `args` is the a tuple of arguments to pass to the exception constructor.
#[inline]
pub fn new_err<'p, A>(py: Token, exc: Py<'p, PyType>, args: A) -> PyErr
pub fn new_err<'p, A>(py: Python, exc: Py<'p, PyType>, args: A) -> PyErr
where A: 'p + ToPyTuple
{
let exc = exc.clone_ref();
@ -254,13 +254,13 @@ impl PyErr {
}
/// Print a standard traceback to sys.stderr.
pub fn print(self, py: Token) {
pub fn print(self, py: Python) {
self.restore(py);
unsafe { ffi::PyErr_PrintEx(0) }
}
/// Print a standard traceback to sys.stderr.
pub fn print_and_set_sys_last_vars(self, py: Token) {
pub fn print_and_set_sys_last_vars(self, py: Python) {
self.restore(py);
unsafe { ffi::PyErr_PrintEx(1) }
}
@ -268,7 +268,7 @@ impl PyErr {
/// Return true if the current exception matches the exception in `exc`.
/// If `exc` is a class object, this also returns `true` when `self` is an instance of a subclass.
/// If `exc` is a tuple, all exceptions in the tuple (and recursively in subtuples) are searched for a match.
pub fn matches<T>(&self, py: Token, exc: T) -> bool
pub fn matches<T>(&self, py: Python, exc: T) -> bool
where T: ToPyObject
{
exc.with_borrowed_ptr(py, |exc| unsafe {
@ -277,7 +277,7 @@ impl PyErr {
}
/// Normalizes the error. This ensures that the exception value is an instance of the exception type.
pub fn normalize(&mut self, py: Token) {
pub fn normalize(&mut self, py: Python) {
// The normalization helper function involves temporarily moving out of the &mut self,
// which requires some unsafe trickery:
unsafe {
@ -288,7 +288,7 @@ impl PyErr {
/// Helper function for normalizing the error by deconstructing and reconstructing the PyErr.
/// Must not panic for safety in normalize()
fn into_normalized(self, py: Token) -> PyErr {
fn into_normalized(self, py: Python) -> PyErr {
let PyErr { ptype, pvalue, ptraceback } = self;
let mut ptype = ptype.into_ptr();
let mut pvalue = pvalue.into_ptr();
@ -300,14 +300,14 @@ impl PyErr {
}
/// Retrieves the exception type.
pub fn get_type<'p>(&self, py: Token<'p>) -> Py<'p, PyType> {
pub fn get_type<'p>(&self, py: Python<'p>) -> Py<'p, PyType> {
self.ptype.as_ref(py)
}
/// 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<'p>(&mut self, py: Token<'p>) -> Py<'p, PyObject> {
pub fn instance<'p>(&mut self, py: Python<'p>) -> Py<'p, PyObject> {
self.normalize(py);
match self.pvalue {
Some(ref instance) => instance.as_ref(py),
@ -318,7 +318,7 @@ impl PyErr {
/// Writes the error back to the Python interpreter's global state.
/// This is the opposite of `PyErr::fetch()`.
#[inline]
pub fn restore(self, _py: Token) {
pub fn restore(self, _py: Python) {
let PyErr { ptype, pvalue, ptraceback } = self;
unsafe {
ffi::PyErr_Restore(ptype.into_ptr(), pvalue.into_ptr(), ptraceback.into_ptr())
@ -327,7 +327,7 @@ impl PyErr {
/// Issue a warning message.
/// May return a PyErr if warnings-as-errors is enabled.
pub fn warn(py: Token, category: &PyObject, message: &str, stacklevel: i32) -> PyResult<()> {
pub fn warn(py: Python, category: &PyObject, message: &str, stacklevel: i32) -> PyResult<()> {
let message = CString::new(message).unwrap();
unsafe {
error_on_minusone(py, ffi::PyErr_WarnEx(
@ -375,7 +375,7 @@ pub fn panic_after_error() -> ! {
/// Returns Ok if the error code is not -1.
#[inline]
pub fn error_on_minusone(py: Token, result: libc::c_int) -> PyResult<()> {
pub fn error_on_minusone(py: Python, result: libc::c_int) -> PyResult<()> {
if result != -1 {
Ok(())
} else {

View File

@ -141,5 +141,5 @@ macro_rules! py_fn_impl {
#[allow(dead_code)]
pub unsafe fn py_fn_impl<'p>(py: Python<'p>,
method_def: *mut ffi::PyMethodDef) -> Py<'p, PyObject> {
Py::from_owned_ptr_or_panic(py.token(), ffi::PyCFunction_New(method_def, ptr::null_mut()))
Py::from_owned_ptr_or_panic(py, ffi::PyCFunction_New(method_def, ptr::null_mut()))
}

View File

@ -69,6 +69,7 @@ pub use pyptr::{Py, PyPtr};
pub use err::{PyErr, PyResult, PyDowncastError};
pub use objects::*;
pub use objectprotocol::ObjectProtocol;
pub use python::{Python, PythonToken, IntoPythonPointer, PythonObjectWithToken};
pub use pythonrun::{GILGuard, GILProtected, prepare_freethreaded_python};
pub use conversion::{FromPyObject, RefFromPyObject, ToPyObject, IntoPyObject, ToPyTuple};
@ -207,10 +208,10 @@ pub unsafe fn py_module_init_impl(
return module;
}
let module = match Py::<PyModule>::cast_from_owned_ptr(py.token(), module) {
let module = match Py::<PyModule>::cast_from_owned_ptr(py, module) {
Ok(m) => m,
Err(e) => {
PyErr::from(e).restore(py.token());
PyErr::from(e).restore(py);
mem::forget(guard);
return ptr::null_mut();
}
@ -218,7 +219,7 @@ pub unsafe fn py_module_init_impl(
let ret = match init(py, &module) {
Ok(()) => module.into_ptr(),
Err(e) => {
e.restore(py.token());
e.restore(py);
ptr::null_mut()
}
};

View File

@ -7,18 +7,121 @@ use std::cmp::Ordering;
use ffi;
use libc;
use pyptr::{Py, PyPtr};
use python::{Python, ToPythonPointer, Token, PythonObjectWithToken};
use python::{Python, ToPythonPointer, PythonObjectWithToken};
use objects::{PyObject, PyDict, PyString};
use conversion::{ToPyObject, ToPyTuple};
use typeob::PyTypeInfo;
use err::{PyErr, PyResult, self};
impl<'p, T> Py<'p, T> {
pub trait ObjectProtocol {
/// Determines whether this object has the given attribute.
/// This is equivalent to the Python expression 'hasattr(self, attr_name)'.
fn hasattr<N>(&self, attr_name: N) -> PyResult<bool> where N: ToPyObject;
/// Retrieves an attribute value.
/// This is equivalent to the Python expression 'self.attr_name'.
fn getattr<N>(&self, attr_name: N) -> PyResult<Py<PyObject>> where N: ToPyObject;
/// Sets an attribute value.
/// This is equivalent to the Python expression 'self.attr_name = value'.
fn setattr<N, V>(&self, attr_name: N, value: V) -> PyResult<()>
where N: ToPyObject, V: ToPyObject;
/// Deletes an attribute.
/// This is equivalent to the Python expression 'del self.attr_name'.
fn delattr<N>(&self, attr_name: N) -> PyResult<()> where N: ToPyObject;
/// Compares two Python objects.
///
/// On Python 2, this is equivalent to the Python expression 'cmp(self, other)'.
///
/// On Python 3, this is equivalent to:
/// ```
/// if self == other:
/// return Equal
/// elif a < b:
/// return Less
/// elif a > b:
/// return Greater
/// else:
/// raise TypeError("ObjectProtocol::compare(): All comparisons returned false")
/// ```
fn compare<O>(&self, other: O) -> PyResult<Ordering> where O: ToPyObject;
/// Compares two Python objects.
///
/// Depending on the value of `compare_op`, equivalent to one of the following Python expressions:
/// * CompareOp::Eq: `self == other`
/// * CompareOp::Ne: `self != other`
/// * CompareOp::Lt: `self < other`
/// * CompareOp::Le: `self <= other`
/// * CompareOp::Gt: `self > other`
/// * CompareOp::Ge: `self >= other`
fn rich_compare<O>(&self, other: O, compare_op: ::CompareOp)
-> PyResult<Py<PyObject>> where O: ToPyObject;
/// Compute the string representation of self.
/// This is equivalent to the Python expression 'repr(self)'.
fn repr(&self) -> PyResult<Py<PyString>>;
/// Compute the string representation of self.
/// This is equivalent to the Python expression 'str(self)'.
fn str(&self) -> PyResult<Py<PyString>>;
/// Determines whether this object is callable.
fn is_callable(&self) -> bool;
/// Calls the object.
/// This is equivalent to the Python expression: 'self(*args, **kwargs)'
fn call<A>(&self, args: A, kwargs: Option<&PyDict>) -> PyResult<Py<PyObject>>
where A: ToPyTuple;
/// 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<Py<PyObject>>
where A: ToPyTuple;
/// Retrieves the hash code of the object.
/// This is equivalent to the Python expression: 'hash(self)'
fn hash(&self) -> PyResult<::Py_hash_t>;
/// Returns whether the object is considered to be true.
/// This is equivalent to the Python expression: 'not not self'
fn is_true(&self) -> PyResult<bool>;
/// Returns the length of the sequence or mapping.
/// This is equivalent to the Python expression: 'len(self)'
fn len(&self) -> PyResult<usize>;
/// This is equivalent to the Python expression: 'self[key]'
fn get_item<K>(&self, key: K) -> PyResult<Py<PyObject>> where K: ToPyObject;
/// Sets an item value.
/// This is equivalent to the Python expression 'self[key] = value'.
fn set_item<K, V>(&self, key: K, value: V) -> PyResult<()>
where K: ToPyObject, V: ToPyObject;
/// Deletes an item.
/// This is equivalent to the Python expression 'del self[key]'.
fn del_item<K>(&self, key: K) -> PyResult<()> where K: ToPyObject;
// /// Takes an object and returns an iterator for it.
// /// This is typically a new iterator but if the argument
// /// is an iterator, this returns itself.
// fn iter<'a>(&'a self) -> PyResult<Py<'p, ::objects::PyIterator<'a>>>;
}
impl<T> ObjectProtocol for T where T: PythonObjectWithToken + ToPythonPointer {
/// Determines whether this object has the given attribute.
/// This is equivalent to the Python expression 'hasattr(self, attr_name)'.
#[inline]
pub fn hasattr<N>(&self, attr_name: N) -> PyResult<bool> where N: ToPyObject {
fn hasattr<N>(&self, attr_name: N) -> PyResult<bool> where N: ToPyObject {
attr_name.with_borrowed_ptr(self.token(), |attr_name| unsafe {
Ok(ffi::PyObject_HasAttr(self.as_ptr(), attr_name) != 0)
})
@ -27,10 +130,10 @@ impl<'p, T> Py<'p, T> {
/// Retrieves an attribute value.
/// This is equivalent to the Python expression 'self.attr_name'.
#[inline]
pub fn getattr<N>(&self, attr_name: N) -> PyResult<PyPtr<PyObject>> where N: ToPyObject
fn getattr<N>(&self, attr_name: N) -> PyResult<Py<PyObject>> where N: ToPyObject
{
attr_name.with_borrowed_ptr(self.token(), |attr_name| unsafe {
PyPtr::from_owned_ptr_or_err(
Py::from_owned_ptr_or_err(
self.token(), ffi::PyObject_GetAttr(self.as_ptr(), attr_name))
})
}
@ -38,7 +141,7 @@ impl<'p, T> Py<'p, T> {
/// Sets an attribute value.
/// This is equivalent to the Python expression 'self.attr_name = value'.
#[inline]
pub fn setattr<N, V>(&self, attr_name: N, value: V) -> PyResult<()>
fn setattr<N, V>(&self, attr_name: N, value: V) -> PyResult<()>
where N: ToPyObject, V: ToPyObject
{
attr_name.with_borrowed_ptr(
@ -52,7 +155,7 @@ impl<'p, T> Py<'p, T> {
/// Deletes an attribute.
/// This is equivalent to the Python expression 'del self.attr_name'.
#[inline]
pub fn delattr<N>(&self, attr_name: N) -> PyResult<()> where N: ToPyObject {
fn delattr<N>(&self, attr_name: N) -> PyResult<()> where N: ToPyObject {
attr_name.with_borrowed_ptr(self.token(), |attr_name| unsafe {
err::error_on_minusone(self.token(),
ffi::PyObject_DelAttr(self.as_ptr(), attr_name))
@ -74,8 +177,8 @@ impl<'p, T> Py<'p, T> {
/// else:
/// raise TypeError("ObjectProtocol::compare(): All comparisons returned false")
/// ```
/*pub fn compare<O>(&self, other: O) -> PyResult<Ordering> where O: ToPyObject {
unsafe fn do_compare(py: Token,
fn compare<O>(&self, other: O) -> PyResult<Ordering> where O: ToPyObject {
unsafe fn do_compare(py: Python,
a: *mut ffi::PyObject,
b: *mut ffi::PyObject) -> PyResult<Ordering> {
let result = ffi::PyObject_RichCompareBool(a, b, ffi::Py_EQ);
@ -99,10 +202,10 @@ impl<'p, T> Py<'p, T> {
return Err(PyErr::new::<::exc::TypeError, _>(py, "ObjectProtocol::compare(): All comparisons returned false"));
}
other.with_borrowed_ptr(self.py(), |other| unsafe {
other.with_borrowed_ptr(self.token(), |other| unsafe {
do_compare(self.token(), self.as_ptr(), other)
})
}*/
}
/// Compares two Python objects.
///
@ -113,8 +216,8 @@ impl<'p, T> Py<'p, T> {
/// * CompareOp::Le: `self <= other`
/// * CompareOp::Gt: `self > other`
/// * CompareOp::Ge: `self >= other`
/*pub fn rich_compare<O>(&self, other: O, compare_op: ::CompareOp)
-> PyResult<PyPtr<PyObject>> where O: ToPyObject {
fn rich_compare<O>(&self, other: O, compare_op: ::CompareOp)
-> PyResult<Py<PyObject>> where O: ToPyObject {
unsafe {
other.with_borrowed_ptr(self.token(), |other| {
Py::cast_from_owned_nullptr(
@ -122,58 +225,65 @@ impl<'p, T> Py<'p, T> {
self.as_ptr(), other, compare_op as libc::c_int))
})
}
}*/
}
/// Compute the string representation of self.
/// This is equivalent to the Python expression 'repr(self)'.
#[inline]
pub fn repr(&'p self) -> PyResult<Py<'p, PyString>> {
fn repr(&self) -> PyResult<Py<PyString>> {
unsafe { Py::cast_from_owned_nullptr(self.token(), ffi::PyObject_Repr(self.as_ptr())) }
}
/// Compute the string representation of self.
/// This is equivalent to the Python expression 'str(self)'.
#[inline]
pub fn str(&'p self) -> PyResult<Py<'p, PyString>> {
fn str(&self) -> PyResult<Py<PyString>> {
unsafe { Py::cast_from_owned_nullptr(self.token(), ffi::PyObject_Str(self.as_ptr())) }
}
/// Determines whether this object is callable.
#[inline]
pub fn is_callable(&self) -> bool {
fn is_callable(&self) -> bool {
unsafe {
ffi::PyCallable_Check(self.as_ptr()) != 0
}
}
/* /// Calls the object.
/// Calls the object.
/// This is equivalent to the Python expression: 'self(*args, **kwargs)'
#[inline]
pub fn call<'a, A>(&self, args: A, kwargs: Option<&PyDict>) -> PyResult<Py<'p, PyObject>>
fn call<A>(&self, args: A, kwargs: Option<&PyDict>) -> PyResult<Py<PyObject>>
where A: ToPyTuple
{
let t = args.to_py_tuple(self.token());
unsafe {
Py::from_owned_ptr_or_err(
self.py(), ffi::PyObject_Call(self.as_ptr(), t.as_ptr(), kwargs.as_ptr()))
self.token(),
ffi::PyObject_Call(self.as_ptr(), t.as_ptr(), kwargs.as_ptr()))
}
}
/// Calls a method on the object.
/// This is equivalent to the Python expression: 'self.name(*args, **kwargs)'
#[inline]
pub fn call_method<A>(&self,
name: &str, args: A,
kwargs: Option<&PyDict>) -> PyResult<Py<'p, PyObject>>
fn call_method<A>(&self,
name: &str, args: A,
kwargs: Option<&PyDict>) -> PyResult<Py<PyObject>>
where A: ToPyTuple
{
self.getattr(name)?.call(args, kwargs)
}*/
name.with_borrowed_ptr(self.token(), |name| unsafe {
let t = args.to_py_tuple(self.token());
let ptr = ffi::PyObject_GetAttr(self.as_ptr(), name);
Py::from_owned_ptr_or_err(
self.token(),
ffi::PyObject_Call(ptr, t.as_ptr(), kwargs.as_ptr()))
})
}
/// Retrieves the hash code of the object.
/// This is equivalent to the Python expression: 'hash(self)'
#[inline]
pub fn hash(&self) -> PyResult<::Py_hash_t> {
fn hash(&self) -> PyResult<::Py_hash_t> {
let v = unsafe { ffi::PyObject_Hash(self.as_ptr()) };
if v == -1 {
Err(PyErr::fetch(self.token()))
@ -185,7 +295,7 @@ impl<'p, T> Py<'p, T> {
/// Returns whether the object is considered to be true.
/// This is equivalent to the Python expression: 'not not self'
#[inline]
pub fn is_true(&self) -> PyResult<bool> {
fn is_true(&self) -> PyResult<bool> {
let v = unsafe { ffi::PyObject_IsTrue(self.as_ptr()) };
if v == -1 {
Err(PyErr::fetch(self.token()))
@ -197,7 +307,7 @@ impl<'p, T> Py<'p, T> {
/// Returns the length of the sequence or mapping.
/// This is equivalent to the Python expression: 'len(self)'
#[inline]
pub fn len(&self) -> PyResult<usize> {
fn len(&self) -> PyResult<usize> {
let v = unsafe { ffi::PyObject_Size(self.as_ptr()) };
if v == -1 {
Err(PyErr::fetch(self.token()))
@ -208,7 +318,7 @@ impl<'p, T> Py<'p, T> {
/// This is equivalent to the Python expression: 'self[key]'
#[inline]
pub fn get_item<K>(&'p self, key: K) -> PyResult<Py<'p, PyObject>> where K: ToPyObject {
fn get_item<K>(&self, key: K) -> PyResult<Py<PyObject>> where K: ToPyObject {
key.with_borrowed_ptr(self.token(), |key| unsafe {
Py::from_owned_ptr_or_err(
self.token(), ffi::PyObject_GetItem(self.as_ptr(), key))
@ -218,7 +328,7 @@ impl<'p, T> Py<'p, T> {
/// Sets an item value.
/// This is equivalent to the Python expression 'self[key] = value'.
#[inline]
pub fn set_item<K, V>(&self, key: K, value: V) -> PyResult<()>
fn set_item<K, V>(&self, key: K, value: V) -> PyResult<()>
where K: ToPyObject, V: ToPyObject
{
key.with_borrowed_ptr(
@ -232,7 +342,7 @@ impl<'p, T> Py<'p, T> {
/// Deletes an item.
/// This is equivalent to the Python expression 'del self[key]'.
#[inline]
pub fn del_item<K>(&self, key: K) -> PyResult<()> where K: ToPyObject {
fn del_item<K>(&self, key: K) -> PyResult<()> where K: ToPyObject {
key.with_borrowed_ptr(self.token(), |key| unsafe {
err::error_on_minusone(self.token(),
ffi::PyObject_DelItem(self.as_ptr(), key))
@ -248,10 +358,8 @@ impl<'p, T> Py<'p, T> {
//}
}
// impl ObjectProtocol for PyObject {}
impl<'p, T> fmt::Debug for Py<'p, T> {
impl<'p, T> fmt::Debug for Py<'p, T> where T: ObjectProtocol + PyTypeInfo {
fn fmt(&self, f : &mut fmt::Formatter) -> Result<(), fmt::Error> {
// TODO: we shouldn't use fmt::Error when repr() fails
let repr_obj = try!(self.repr().map_err(|_| fmt::Error));
@ -259,7 +367,7 @@ impl<'p, T> fmt::Debug for Py<'p, T> {
}
}
impl<'p, T> fmt::Display for Py<'p, T> {
impl<'p, T> fmt::Display for Py<'p, T> where T: ObjectProtocol + PyTypeInfo {
fn fmt(&self, f : &mut fmt::Formatter) -> Result<(), fmt::Error> {
// TODO: we shouldn't use fmt::Error when str() fails
let str_obj = try!(self.str().map_err(|_| fmt::Error));
@ -267,26 +375,26 @@ impl<'p, T> fmt::Display for Py<'p, T> {
}
}
impl<T> fmt::Debug for PyPtr<T> {
impl<'p, T> fmt::Debug for PyPtr<T> where T: ObjectProtocol + PyTypeInfo {
default fn fmt(&self, f : &mut fmt::Formatter) -> Result<(), fmt::Error> {
let gil = Python::acquire_gil();
let py = gil.python();
// TODO: we shouldn't use fmt::Error when repr() fails
let r = self.as_ref(py.token());
let r = self.as_ref(py);
let repr_obj = try!(r.repr().map_err(|_| fmt::Error));
f.write_str(&repr_obj.to_string_lossy())
}
}
impl<T> fmt::Display for PyPtr<T> {
impl<'p, T> fmt::Display for PyPtr<T> where T: ObjectProtocol + PyTypeInfo {
default fn fmt(&self, f : &mut fmt::Formatter) -> Result<(), fmt::Error> {
let gil = Python::acquire_gil();
let py = gil.python();
// TODO: we shouldn't use fmt::Error when repr() fails
let r = self.as_ref(py.token());
let repr_obj = try!(r.str().map_err(|_| fmt::Error));
let r = self.as_ref(py);
let repr_obj = try!(r.as_ref().str().map_err(|_| fmt::Error));
f.write_str(&repr_obj.to_string_lossy())
}
}

View File

@ -1,6 +1,6 @@
use ::{Py, PyPtr, PyObject};
use ::{PyPtr, PyObject};
use ffi;
use python::{Python, PythonToken, ToPythonPointer, Token};
use python::{PythonToken, ToPythonPointer, Python};
use conversion::{ToPyObject};
/// Represents a Python `bool`.
@ -11,7 +11,7 @@ pyobject_newtype!(PyBool, PyBool_Check, PyBool_Type);
impl PyBool {
/// Depending on `val`, returns `py.True()` or `py.False()`.
#[inline]
pub fn get(py: Token, val: bool) -> PyPtr<PyBool> {
pub fn get(py: Python, val: bool) -> PyPtr<PyBool> {
if val { py.True() } else { py.False() }
}
@ -25,12 +25,12 @@ impl PyBool {
/// Converts a rust `bool` to a Python `bool`.
impl ToPyObject for bool {
#[inline]
fn to_object(&self, py: Token) -> PyPtr<PyObject> {
fn to_object(&self, py: Python) -> PyPtr<PyObject> {
PyBool::get(py, *self).into_object()
}
#[inline]
fn with_borrowed_ptr<F, R>(&self, _py: Token, f: F) -> R
fn with_borrowed_ptr<F, R>(&self, _py: Python, f: F) -> R
where F: FnOnce(*mut ffi::PyObject) -> R
{
// Avoid unnecessary Py_INCREF/Py_DECREF pair

View File

@ -4,7 +4,7 @@ use std;
use std::ptr;
use std::os::raw::c_char;
use ffi;
use python::{Python, PythonToken, ToPythonPointer, Token};
use python::{PythonToken, ToPythonPointer, Python, PythonObjectWithToken};
use objects::PyObject;
use err::{PyResult, PyErr};
use pyptr::Py;
@ -20,7 +20,7 @@ impl PyByteArray {
/// The byte string is initialized by copying the data from the `&[u8]`.
///
/// Panics if out of memory.
pub fn new<'p>(py: Token<'p>, src: &[u8]) -> Py<'p, PyByteArray> {
pub fn new<'p>(py: Python<'p>, src: &[u8]) -> Py<'p, PyByteArray> {
let ptr = src.as_ptr() as *const c_char;
let len = src.len() as ffi::Py_ssize_t;
let ptr = unsafe {ffi::PyByteArray_FromStringAndSize(ptr, len)};
@ -29,12 +29,12 @@ impl PyByteArray {
/// Creates a new Python bytearray object
/// from other PyObject, that implements the buffer protocol.
pub fn from<'p>(py: Python<'p>, src: Py<PyObject>) -> PyResult<Py<'p, PyByteArray>> {
pub fn from<'p>(src: Py<'p, PyObject>) -> PyResult<Py<'p, PyByteArray>> {
let res = unsafe {ffi::PyByteArray_FromObject(src.as_ptr())};
if res != ptr::null_mut() {
Ok(unsafe{Py::cast_from_owned_ptr_or_panic(py, res)})
Ok(unsafe{Py::cast_from_owned_ptr_or_panic(src.token(), res)})
} else {
Err(PyErr::fetch(py))
Err(PyErr::fetch(src.token()))
}
}
@ -63,7 +63,7 @@ impl PyByteArray {
if result == 0 {
Ok(())
} else {
Err(PyErr::fetch(self.py()))
Err(PyErr::fetch(self.token()))
}
}
}

View File

@ -4,7 +4,7 @@
use ffi;
use pyptr::{Py, PyPtr};
use python::{Python, Token, PythonToken, ToPythonPointer, PythonObjectWithToken};
use python::{Python, PythonToken, ToPythonPointer, PythonObjectWithToken};
use conversion::ToPyObject;
use objects::{PyObject}; //, PyList};
use err::{self, PyResult, PyErr};
@ -20,7 +20,7 @@ impl PyDict {
/// Creates a new empty dictionary.
///
/// May panic when running out of memory.
pub fn new(py: Token) -> Py<PyDict> {
pub fn new(py: Python) -> Py<PyDict> {
unsafe { Py::from_owned_ptr_or_panic(py, ffi::PyDict_New()) }
}
@ -113,16 +113,16 @@ impl PyDict {
}
}
/*impl <K, V> ToPyObject for collections::HashMap<K, V>
impl <K, V> ToPyObject for collections::HashMap<K, V>
where K: hash::Hash+cmp::Eq+ToPyObject,
V: ToPyObject
{
fn to_object(&self, py: Token) -> PyPtr<PyObject> {
fn to_object(&self, py: Python) -> PyPtr<PyObject> {
let dict = PyDict::new(py);
for (key, value) in self {
dict.set_item(key, value).unwrap();
};
dict.into_object()
dict.into_object_pptr()
}
}
@ -130,14 +130,14 @@ impl <K, V> ToPyObject for collections::BTreeMap<K, V>
where K: cmp::Eq+ToPyObject,
V: ToPyObject
{
fn to_object(&self, py: Token) -> PyPtr<PyObject> {
fn to_object(&self, py: Python) -> PyPtr<PyObject> {
let dict = PyDict::new(py);
for (key, value) in self {
dict.set_item(key, value).unwrap();
};
dict.into_pptr().into_object()
dict.into_object_pptr()
}
}*/
}
#[cfg(test)]
mod test {

View File

@ -10,7 +10,7 @@ use std::ffi::CStr;
use ffi;
use pyptr::{Py, PyPtr};
use python::{Python, ToPythonPointer, Token};
use python::{Python, ToPythonPointer};
use err::PyResult;
use super::tuple::PyTuple;
use super::typeobject::PyType;
@ -23,7 +23,7 @@ macro_rules! exc_type(
impl $crate::PyTypeObject for $name {
#[inline]
fn type_object(py: $crate::python::Token) -> $crate::PyPtr<PyType> {
fn type_object(py: $crate::python::Python) -> $crate::PyPtr<PyType> {
unsafe { PyType::from_type_ptr(py, ffi::$exc_name as *mut ffi::PyTypeObject) }
}
}
@ -84,7 +84,7 @@ exc_type!(UnicodeTranslateError, PyExc_UnicodeTranslateError);
impl UnicodeDecodeError {
pub fn new(py: Token, encoding: &CStr, input: &[u8], range: ops::Range<usize>, reason: &CStr)
pub fn new(py: Python, encoding: &CStr, input: &[u8], range: ops::Range<usize>, reason: &CStr)
-> PyResult<PyPtr<UnicodeDecodeError>> {
unsafe {
let input: &[c_char] = mem::transmute(input);
@ -99,7 +99,7 @@ impl UnicodeDecodeError {
}
}
pub fn new_utf8<'p>(py: Token, input: &[u8], err: std::str::Utf8Error)
pub fn new_utf8<'p>(py: Python, input: &[u8], err: std::str::Utf8Error)
-> PyResult<PyPtr<UnicodeDecodeError>>
{
let pos = err.valid_up_to();

View File

@ -6,13 +6,13 @@ pub use self::module::PyModule;
pub use self::string::{PyBytes, PyString, PyStringData};
//pub use self::iterator::PyIterator;
pub use self::boolobject::PyBool;
//pub use self::bytearray::PyByteArray;
pub use self::bytearray::PyByteArray;
pub use self::tuple::{PyTuple, NoArgs};
pub use self::dict::PyDict;
//pub use self::list::PyList;
pub use self::num::{PyLong, PyFloat};
//pub use self::sequence::PySequence;
//pub use self::slice::PySlice;
pub use self::slice::PySlice;
//pub use self::set::{PySet, PyFrozenSet};
@ -44,7 +44,7 @@ macro_rules! pyobject_newtype(
}
impl $crate::python::PythonObjectWithToken for $name {
fn token<'p>(&'p self) -> $crate::python::Token<'p> {
fn token<'p>(&'p self) -> $crate::python::Python<'p> {
self.0.token()
}
}
@ -98,12 +98,12 @@ mod string;
mod dict;
//mod iterator;
mod boolobject;
//mod bytearray;
mod bytearray;
mod tuple;
//mod list;
mod num;
//mod sequence;
//mod slice;
mod slice;
// mod set;
mod object;
pub mod exc;

View File

@ -8,10 +8,12 @@ use std::os::raw::c_char;
use std::ffi::{CStr, CString};
use pyptr::{Py, PyPtr};
use python::{Python, PythonToken, ToPythonPointer, PythonObjectWithToken, Token};
use objects::{PyObject, PyDict, PyType, exc};
use python::{PythonToken, ToPythonPointer, PythonObjectWithToken, Python};
use objects::{PyDict, PyType, exc};
use objectprotocol::ObjectProtocol;
use err::{PyResult, PyErr};
/// Represents a Python module object.
pub struct PyModule(PythonToken<PyModule>);
@ -19,7 +21,7 @@ pyobject_newtype!(PyModule, PyModule_Check, PyModule_Type);
impl PyModule {
/// Create a new module object with the `__name__` attribute set to name.
pub fn new<'p>(py: Token<'p>, name: &str) -> PyResult<Py<'p, PyModule>> {
pub fn new<'p>(py: Python<'p>, name: &str) -> PyResult<Py<'p, PyModule>> {
let name = CString::new(name).unwrap();
unsafe {
Py::cast_from_owned_nullptr(py, ffi::PyModule_New(name.as_ptr()))
@ -27,7 +29,7 @@ impl PyModule {
}
/// Import the Python module with the specified name.
pub fn import<'p>(py: Token<'p>, name: &str) -> PyResult<Py<'p, PyModule>> {
pub fn import<'p>(py: Python<'p>, name: &str) -> PyResult<Py<'p, PyModule>> {
let name = CString::new(name).unwrap();
unsafe {
Py::cast_from_owned_nullptr(py, ffi::PyImport_ImportModule(name.as_ptr()))
@ -92,7 +94,6 @@ impl PyModule {
unsafe { PyType::from_type_ptr(self.token(), ty) }
};
// PyObject::from_borrowed_ptr(self.py(), self.as_ptr()).setattr(type_name, ty)
Ok(())
self.setattr(type_name, ty)
}
}

View File

@ -12,7 +12,7 @@ use ffi;
use super::exc;
use super::PyObject;
use typeob::PyTypeInfo;
use python::{Python, PythonToken, ToPythonPointer, PythonObjectWithToken, Token};
use python::{PythonToken, ToPythonPointer, Python};
use err::{PyResult, PyErr};
use conversion::{ToPyObject, FromPyObject};
@ -37,7 +37,7 @@ pyobject_newtype!(PyFloat, PyFloat_Check, PyFloat_Type);
impl PyFloat {
/// Creates a new Python `float` object.
pub fn new(_py: Token, val: c_double) -> PyPtr<PyFloat> {
pub fn new(_py: Python, val: c_double) -> PyPtr<PyFloat> {
unsafe {
PyPtr::from_owned_ptr_or_panic(ffi::PyFloat_FromDouble(val))
}
@ -53,7 +53,7 @@ impl PyFloat {
macro_rules! int_fits_c_long(
($rust_type:ty) => (
impl ToPyObject for $rust_type {
fn to_object(&self, py: Token) -> PyPtr<PyObject> {
fn to_object(&self, _py: Python) -> PyPtr<PyObject> {
unsafe {
PyPtr::from_owned_ptr_or_panic(ffi::PyLong_FromLong(*self as c_long))
}
@ -78,7 +78,7 @@ macro_rules! int_fits_larger_int(
($rust_type:ty, $larger_type:ty) => (
impl ToPyObject for $rust_type {
#[inline]
fn to_object(&self, py: Token) -> PyPtr<PyObject> {
fn to_object(&self, py: Python) -> PyPtr<PyObject> {
(*self as $larger_type).to_object(py)
}
}
@ -96,7 +96,7 @@ macro_rules! int_fits_larger_int(
fn err_if_invalid_value<'p, T: PartialEq>
(py: Token, invalid_value: T, actual_value: T) -> PyResult<T>
(py: Python, invalid_value: T, actual_value: T) -> PyResult<T>
{
if actual_value == invalid_value && PyErr::occurred(py) {
Err(PyErr::fetch(py))
@ -109,7 +109,7 @@ 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: Token) -> PyPtr<PyObject> {
fn to_object(&self, _py: Python) -> PyPtr<PyObject> {
unsafe {
PyPtr::from_owned_ptr_or_panic($pylong_from_ll_or_ull(*self))
}
@ -169,7 +169,7 @@ int_fits_larger_int!(usize, u64);
int_convert_u64_or_i64!(u64, ffi::PyLong_FromUnsignedLongLong, ffi::PyLong_AsUnsignedLongLong);
impl ToPyObject for f64 {
fn to_object(&self, py: Token) -> PyPtr<PyObject> {
fn to_object(&self, py: Python) -> PyPtr<PyObject> {
PyFloat::new(py, *self).into_object()
}
}
@ -183,12 +183,12 @@ pyobject_extract!(obj to f64 => {
}
});
fn overflow_error(py: Token) -> PyErr {
fn overflow_error(py: Python) -> PyErr {
PyErr::new_lazy_init(py.get_type::<exc::OverflowError>(), None)
}
impl ToPyObject for f32 {
fn to_object(&self, py: Token) -> PyPtr<PyObject> {
fn to_object(&self, py: Python) -> PyPtr<PyObject> {
PyFloat::new(py, *self as f64).into_object()
}
}

View File

@ -4,8 +4,8 @@ use std;
use ffi;
use pyptr::{Py, PyPtr};
use err::{PyErr, PyResult, PyDowncastError};
use python::{Python, PythonToken, Token, PythonObjectWithToken};
use err::{PyDowncastError};
use python::{PythonToken, Python, PythonObjectWithToken};
use typeob::PyTypeInfo;
pub struct PyObject(PythonToken<PyObject>);
@ -15,12 +15,12 @@ pyobject_newtype!(PyObject, PyObject_Check, PyBaseObject_Type);
impl PyObject {
#[inline]
pub fn from_owned_ptr(py: Token, ptr: *mut ffi::PyObject) -> Py<PyObject> {
pub fn from_owned_ptr(py: Python, ptr: *mut ffi::PyObject) -> Py<PyObject> {
unsafe { Py::from_owned_ptr(py, ptr) }
}
#[inline]
pub fn from_borrowed_ptr(py: Token, ptr: *mut ffi::PyObject) -> Py<PyObject> {
pub fn from_borrowed_ptr(py: Python, ptr: *mut ffi::PyObject) -> Py<PyObject> {
unsafe { Py::from_borrowed_ptr(py, ptr) }
}
@ -28,7 +28,7 @@ impl PyObject {
/// This moves ownership over the pointer into the PyObject.
/// Returns None for null pointers; undefined behavior if the pointer is invalid.
#[inline]
pub unsafe fn from_owned_pptr_opt(py: Token, ptr: *mut ffi::PyObject)
pub unsafe fn from_owned_pptr_opt(py: Python, ptr: *mut ffi::PyObject)
-> Option<PyPtr<PyObject>> {
if ptr.is_null() {
None
@ -39,7 +39,7 @@ impl PyObject {
/// Returns None for null pointers; undefined behavior if the pointer is invalid.
#[inline]
pub unsafe fn from_borrowed_pptr_opt(py: Token, ptr: *mut ffi::PyObject)
pub unsafe fn from_borrowed_pptr_opt(py: Python, ptr: *mut ffi::PyObject)
-> Option<PyPtr<PyObject>> {
if ptr.is_null() {
None
@ -64,13 +64,11 @@ impl PyObject {
{
unsafe {
let ptr = self as *const _ as *mut _;
let checked = unsafe { ffi::PyObject_TypeCheck(ptr, D::type_object()) != 0 };
let checked = ffi::PyObject_TypeCheck(ptr, D::type_object()) != 0;
if checked {
Ok(
unsafe {
let ptr = ptr as *mut D;
ptr.as_ref().unwrap() })
let ptr = ptr as *mut D;
Ok(ptr.as_ref().unwrap())
} else {
Err(PyDowncastError(self.token(), None))
}

View File

@ -1,9 +1,9 @@
// Copyright (c) 2017-present PyO3 Project and Contributors
use std::os::raw::c_long;
use pyptr::PyPtr;
use pyptr::{Py, PyPtr};
use objects::PyObject;
use python::{Python, PythonToken, ToPythonPointer, Token};
use python::{PythonToken, ToPythonPointer, Python, PythonObjectWithToken};
use err::{PyErr, PyResult};
use ffi::{self, Py_ssize_t};
use conversion::ToPyObject;
@ -36,12 +36,12 @@ pyobject_newtype!(PySlice, PySlice_Check, PySlice_Type);
impl PySlice {
/// Construct a new slice with the given elements.
pub fn new<'p>(py: Token, start: isize, stop: isize, step: isize) -> PyPtr<PySlice> {
pub fn new<'p>(py: Python<'p>, start: isize, stop: isize, step: isize) -> Py<'p, PySlice> {
unsafe {
let ptr = ffi::PySlice_New(ffi::PyLong_FromLong(start as i64),
ffi::PyLong_FromLong(stop as i64),
ffi::PyLong_FromLong(step as i64));
PyPtr::from_owned_ptr_or_panic(py, ptr)
Py::from_owned_ptr_or_panic(py, ptr)
}
}
@ -75,7 +75,7 @@ impl PySlice {
}
impl ToPyObject for PySliceIndices {
fn to_object<'p>(&self, py: Token) -> PyPtr<PyObject> {
PySlice::new(py, self.start, self.stop, self.step)
fn to_object<'p>(&self, py: Python) -> PyPtr<PyObject> {
PySlice::new(py, self.start, self.stop, self.step).into_object_pptr()
}
}

View File

@ -10,7 +10,7 @@ use std::os::raw::c_char;
use ::{Py, PyPtr};
use ffi;
use python::{Python, PythonToken, ToPythonPointer, Token, PythonObjectWithToken};
use python::{PythonToken, ToPythonPointer, Python, PythonObjectWithToken};
use super::{exc, PyObject};
use err::{PyResult, PyErr};
use conversion::{ToPyObject, RefFromPyObject};
@ -63,7 +63,7 @@ impl <'a> PyStringData<'a> {
/// For Latin-1, UTF-16 and UTF-32, returns an owned string.
///
/// Fails with UnicodeDecodeError if the string data isn't valid in its encoding.
pub fn to_string(self, py: Token) -> PyResult<Cow<'a, str>> {
pub fn to_string(self, py: Python) -> PyResult<Cow<'a, str>> {
match self {
PyStringData::Utf8(data) => {
match str::from_utf8(data) {
@ -141,7 +141,7 @@ impl PyString {
/// Use `PyUnicode::new()` to always create a unicode string.
///
/// Panics if out of memory.
pub fn new<'p>(py: Token, s: &str) -> PyPtr<PyString> {
pub fn new<'p>(_py: Python, s: &str) -> PyPtr<PyString> {
let ptr = s.as_ptr() as *const c_char;
let len = s.len() as ffi::Py_ssize_t;
unsafe {
@ -196,7 +196,7 @@ impl PyBytes {
/// The byte string is initialized by copying the data from the `&[u8]`.
///
/// Panics if out of memory.
pub fn new<'p>(py: Token<'p>, s: &[u8]) -> Py<'p, PyBytes> {
pub fn new<'p>(py: Python<'p>, s: &[u8]) -> Py<'p, PyBytes> {
let ptr = s.as_ptr() as *const c_char;
let len = s.len() as ffi::Py_ssize_t;
unsafe {
@ -219,7 +219,7 @@ impl PyBytes {
/// See `PyString::new` for details on the conversion.
impl ToPyObject for str {
#[inline]
fn to_object(&self, py: Token) -> PyPtr<PyObject> {
fn to_object(&self, py: Python) -> PyPtr<PyObject> {
PyString::new(py, self).into_object()
}
}
@ -228,7 +228,7 @@ impl ToPyObject for str {
/// See `PyString::new` for details on the conversion.
impl <'a> ToPyObject for Cow<'a, str> {
#[inline]
fn to_object(&self, py: Token) -> PyPtr<PyObject> {
fn to_object(&self, py: Python) -> PyPtr<PyObject> {
PyString::new(py, self).into_object()
}
}
@ -237,7 +237,7 @@ 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: Token) -> PyPtr<PyObject> {
fn to_object(&self, py: Python) -> PyPtr<PyObject> {
PyString::new(py, self).into_object()
}
}

View File

@ -6,7 +6,7 @@ use std::slice;
use ::{Py, PyPtr};
use ffi::{self, Py_ssize_t};
use python::{Python, PythonToken, Token,
use python::{PythonToken, Python,
ToPythonPointer, IntoPythonPointer, PythonObjectWithToken};
use err::{PyErr, PyResult};
use conversion::{FromPyObject, ToPyObject, ToPyTuple};
@ -20,7 +20,7 @@ pyobject_newtype!(PyTuple, PyTuple_Check, PyTuple_Type);
impl PyTuple {
/// Construct a new tuple with the given elements.
pub fn new<'p, T: ToPyObject>(py: Token, elements: &[T]) -> PyPtr<PyTuple> {
pub fn new<'p, T: ToPyObject>(py: Python, elements: &[T]) -> PyPtr<PyTuple> {
unsafe {
let len = elements.len();
let ptr = ffi::PyTuple_New(len as Py_ssize_t);
@ -33,7 +33,7 @@ impl PyTuple {
}
/// Retrieves the empty tuple.
pub fn empty(py: Token) -> PyPtr<PyTuple> {
pub fn empty(_py: Python) -> PyPtr<PyTuple> {
unsafe {
PyPtr::from_owned_ptr_or_panic(ffi::PyTuple_New(0))
}
@ -81,21 +81,19 @@ impl PyTuple {
//}
}
use std;
impl<'a> ToPyTuple for Py<'a, PyTuple> {
fn to_py_tuple(&self, _py: Token) -> PyPtr<PyTuple> {
fn to_py_tuple(&self, _py: Python) -> PyPtr<PyTuple> {
self.as_pptr()
}
}
impl<'a> ToPyTuple for &'a str {
fn to_py_tuple(&self, py: Token) -> PyPtr<PyTuple> {
fn to_py_tuple(&self, py: Python) -> PyPtr<PyTuple> {
PyTuple::new(py, &[py_coerce_expr!(self.to_object(py))])
}
}
fn wrong_tuple_length(py: Token, t: &PyTuple, expected_length: usize) -> PyErr {
fn wrong_tuple_length(py: Python, t: &PyTuple, expected_length: usize) -> PyErr {
let msg = format!("Expected tuple of length {}, but got tuple of length {}.",
expected_length, t.len());
PyErr::new_lazy_init(
@ -104,7 +102,7 @@ fn wrong_tuple_length(py: Token, 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: Token) -> PyPtr<PyObject> {
fn to_object<'p>(&self, py: Python<'p>) -> PyPtr<PyObject> {
PyTuple::new(py, &[
$(py_coerce_expr!(self.$n.to_object(py)),)+
]).into_object()
@ -112,7 +110,7 @@ macro_rules! tuple_conversion ({$length:expr,$(($refN:ident, $n:tt, $T:ident)),+
}
impl <$($T: ToPyObject),+> ToPyTuple for ($($T,)+) {
fn to_py_tuple(&self, py: Token) -> PyPtr<PyTuple> {
fn to_py_tuple<'p>(&self, py: Python<'p>) -> PyPtr<PyTuple> {
PyTuple::new(py, &[
$(py_coerce_expr!(self.$n.to_object(py)),)+
])
@ -169,7 +167,7 @@ pub struct NoArgs;
/// Converts `NoArgs` to an empty Python tuple.
impl ToPyObject for NoArgs {
fn to_object(&self, py: Token) -> PyPtr<PyObject> {
fn to_object(&self, py: Python) -> PyPtr<PyObject> {
PyTuple::empty(py).into_object()
}
}
@ -177,7 +175,7 @@ impl ToPyObject for NoArgs {
/// Converts `NoArgs` to an empty Python tuple.
impl ToPyTuple for NoArgs {
fn to_py_tuple(&self, py: Token) -> PyPtr<PyTuple> {
fn to_py_tuple(&self, py: Python) -> PyPtr<PyTuple> {
PyTuple::empty(py)
}
}
@ -185,7 +183,7 @@ impl ToPyTuple for NoArgs {
/// Converts `()` to an empty Python tuple.
impl ToPyTuple for () {
fn to_py_tuple(&self, py: Token) -> PyPtr<PyTuple> {
fn to_py_tuple(&self, py: Python) -> PyPtr<PyTuple> {
PyTuple::empty(py)
}
}

View File

@ -6,8 +6,8 @@ use std::ffi::CStr;
use std::borrow::Cow;
use ffi;
use pyptr::{Py, PyPtr};
use python::{Python, PythonToken, ToPythonPointer, Token, PythonObjectWithToken};
use pyptr::{PyPtr};
use python::{Python, PythonToken, ToPythonPointer, PythonObjectWithToken};
use conversion::ToPyTuple;
use objects::{PyObject, PyDict};
use err::PyResult;
@ -28,7 +28,7 @@ impl PyType {
/// This increments the reference count on the type object.
/// Undefined behavior if the pointer is NULL or invalid.
#[inline]
pub unsafe fn from_type_ptr(_py: Token, p: *mut ffi::PyTypeObject) -> PyPtr<PyType> {
pub unsafe fn from_type_ptr(_py: Python, p: *mut ffi::PyTypeObject) -> PyPtr<PyType> {
PyPtr::from_borrowed_ptr(p as *mut ffi::PyObject)
}

View File

@ -8,12 +8,11 @@ use std::convert::{AsRef, AsMut};
use ffi;
use err::{PyErr, PyResult, PyDowncastError};
use conversion::{ToPyObject, IntoPyObject};
use python::{Python, ToPythonPointer, IntoPythonPointer, Token, PythonObjectWithToken};
use python::{Python, ToPythonPointer, IntoPythonPointer};
use objects::PyObject;
use typeob::{PyTypeInfo, PyObjectAlloc};
#[derive(Debug)]
pub struct PyPtr<T> {
inner: *mut ffi::PyObject,
_t: PhantomData<T>,
@ -33,7 +32,7 @@ impl<T> PyPtr<T> {
/// returns a new reference (owned pointer).
/// Returns `Err(PyErr)` if the pointer is `null`.
/// Unsafe because the pointer might be invalid.
pub unsafe fn from_owned_ptr_or_err(py: Token, ptr: *mut ffi::PyObject) -> PyResult<PyPtr<T>>
pub unsafe fn from_owned_ptr_or_err(py: Python, ptr: *mut ffi::PyObject) -> PyResult<PyPtr<T>>
{
if ptr.is_null() {
Err(PyErr::fetch(py))
@ -67,7 +66,7 @@ impl<T> PyPtr<T> {
/// Creates a Py instance for the given FFI pointer.
/// Calls Py_INCREF() on the ptr.
#[inline]
pub unsafe fn from_borrowed_ptr_opt(_py: Token,
pub unsafe fn from_borrowed_ptr_opt(_py: Python,
ptr: *mut ffi::PyObject) -> Option<PyPtr<T>> {
if ptr.is_null() {
None
@ -78,11 +77,11 @@ impl<T> PyPtr<T> {
}
}
pub fn as_ref<'p>(&self, py: Token<'p>) -> Py<'p, T> {
pub fn as_ref<'p>(&self, py: Python<'p>) -> Py<'p, T> {
unsafe { Py::from_borrowed_ptr(py, self.inner) }
}
pub fn into_ref<'p>(self, py: Token<'p>) -> Py<'p, T> {
pub fn into_ref<'p>(self, py: Python<'p>) -> Py<'p, T> {
let p = Py{inner: self.inner, _t: PhantomData, py: py};
std::mem::forget(self);
p
@ -142,7 +141,7 @@ impl<T> IntoPythonPointer for PyPtr<T> {
impl<T> IntoPyObject for PyPtr<T> {
#[inline]
fn into_object<'a>(self, py: Token) -> PyPtr<PyObject> {
fn into_object<'a>(self, _py: Python) -> PyPtr<PyObject> {
self.into_object()
}
}
@ -168,7 +167,7 @@ impl<T> Drop for PyPtr<T> {
pub struct Py<'p, T> {
pub inner: *mut ffi::PyObject,
_t: PhantomData<T>,
py: Token<'p>,
py: Python<'p>,
}
impl<'p, T> Py<'p, T>
@ -177,14 +176,14 @@ impl<'p, T> Py<'p, T>
/// This moves ownership over the pointer into the Py.
/// Undefined behavior if the pointer is NULL or invalid.
#[inline]
pub unsafe fn from_owned_ptr(py: Token<'p>, ptr: *mut ffi::PyObject) -> Py<'p, T> {
pub unsafe fn from_owned_ptr(py: Python<'p>, ptr: *mut ffi::PyObject) -> Py<'p, T> {
debug_assert!(!ptr.is_null() && ffi::Py_REFCNT(ptr) > 0);
Py {inner: ptr, _t: PhantomData, py: py}
}
/// Cast from ffi::PyObject ptr to a concrete object.
#[inline]
pub unsafe fn from_owned_ptr_or_panic(py: Token<'p>, ptr: *mut ffi::PyObject) -> Py<'p, T>
pub unsafe fn from_owned_ptr_or_panic(py: Python<'p>, ptr: *mut ffi::PyObject) -> Py<'p, T>
{
if ptr.is_null() {
::err::panic_after_error();
@ -197,7 +196,7 @@ impl<'p, T> Py<'p, T>
/// returns a new reference (owned pointer).
/// Returns `Err(PyErr)` if the pointer is `null`.
/// Unsafe because the pointer might be invalid.
pub unsafe fn from_owned_ptr_or_err(py: Token<'p>, ptr: *mut ffi::PyObject)
pub unsafe fn from_owned_ptr_or_err(py: Python<'p>, ptr: *mut ffi::PyObject)
-> PyResult<Py<'p, T>>
{
if ptr.is_null() {
@ -211,7 +210,7 @@ impl<'p, T> Py<'p, T>
/// Calls Py_INCREF() on the ptr.
/// Undefined behavior if the pointer is NULL or invalid.
#[inline]
pub unsafe fn from_borrowed_ptr(py: Token<'p>, ptr: *mut ffi::PyObject) -> Py<'p, T> {
pub unsafe fn from_borrowed_ptr(py: Python<'p>, ptr: *mut ffi::PyObject) -> Py<'p, T> {
debug_assert!(!ptr.is_null() && ffi::Py_REFCNT(ptr) > 0);
ffi::Py_INCREF(ptr);
Py {inner: ptr, _t: PhantomData, py: py}
@ -220,7 +219,7 @@ impl<'p, T> Py<'p, T>
/// Creates a Py instance for the given FFI pointer.
/// Calls Py_INCREF() on the ptr.
#[inline]
pub unsafe fn from_borrowed_ptr_opt(py: Token<'p>,
pub unsafe fn from_borrowed_ptr_opt(py: Python<'p>,
ptr: *mut ffi::PyObject) -> Option<Py<'p, T>> {
if ptr.is_null() {
None
@ -255,6 +254,15 @@ impl<'p, T> Py<'p, T>
ptr
}
/// Consumes a Py<T> instance and creates a PyPtr<PyObject> instance.
/// Ownership moves over to the PyPtr<T> instance, Does not call Py_INCREF() on the ptr.
#[inline]
pub fn into_object_pptr(self) -> PyPtr<PyObject> {
let ptr = PyPtr { inner: self.inner, _t: PhantomData };
std::mem::forget(self);
ptr
}
/// Converts Py<'p, T> -> Py<'p, PyObject>
/// Consumes `self` without calling `Py_DECREF()`
#[inline]
@ -279,7 +287,7 @@ impl<'p, T> Py<'p, T>
Py {inner: self.inner, _t: self._t, py: self.py}
}
pub fn token<'a>(&'a self) -> Token<'p> {
pub fn token<'a>(&'a self) -> Python<'p> {
self.py
}
}
@ -288,7 +296,7 @@ impl<'p, T> Py<'p, T>
impl<'p, T> Py<'p, T> where T: PyTypeInfo
{
/// Create new python object and move T instance under python management
pub fn new(py: Token<'p>, value: T) -> PyResult<Py<'p, T>> where T: PyObjectAlloc<Type=T>
pub fn new(py: Python<'p>, value: T) -> PyResult<Py<'p, T>> where T: PyObjectAlloc<Type=T>
{
let ob = unsafe {
try!(<T as PyObjectAlloc>::alloc(py, value))
@ -298,7 +306,7 @@ impl<'p, T> Py<'p, T> where T: PyTypeInfo
/// Cast from ffi::PyObject ptr to a concrete object.
#[inline]
pub fn cast_from_borrowed_ptr(py: Token<'p>, ptr: *mut ffi::PyObject)
pub fn cast_from_borrowed_ptr(py: Python<'p>, ptr: *mut ffi::PyObject)
-> Result<Py<'p, T>, ::PyDowncastError<'p>>
{
let checked = unsafe { ffi::PyObject_TypeCheck(ptr, T::type_object()) != 0 };
@ -312,7 +320,7 @@ impl<'p, T> Py<'p, T> where T: PyTypeInfo
/// Cast from ffi::PyObject ptr to a concrete object.
#[inline]
pub fn cast_from_owned_ptr(py: Token<'p>, ptr: *mut ffi::PyObject)
pub fn cast_from_owned_ptr(py: Python<'p>, ptr: *mut ffi::PyObject)
-> Result<Py<'p, T>, ::PyDowncastError<'p>>
{
let checked = unsafe { ffi::PyObject_TypeCheck(ptr, T::type_object()) != 0 };
@ -326,7 +334,7 @@ impl<'p, T> Py<'p, T> where T: PyTypeInfo
/// Cast from ffi::PyObject ptr to a concrete object.
#[inline]
pub unsafe fn cast_from_owned_ptr_or_panic(py: Token<'p>,
pub unsafe fn cast_from_owned_ptr_or_panic(py: Python<'p>,
ptr: *mut ffi::PyObject) -> Py<'p, T>
{
if ffi::PyObject_TypeCheck(ptr, T::type_object()) != 0 {
@ -336,7 +344,7 @@ impl<'p, T> Py<'p, T> where T: PyTypeInfo
}
}
pub fn cast_from_owned_nullptr(py: Token<'p>, ptr: *mut ffi::PyObject)
pub fn cast_from_owned_nullptr(py: Python<'p>, ptr: *mut ffi::PyObject)
-> PyResult<Py<'p, T>>
{
if ptr.is_null() {
@ -434,7 +442,7 @@ impl<'p, T> Py<'p, T> where T: PyTypeInfo
//impl<'p, T> PythonObjectWithToken for Py<'p, T> {
// fn token(&self) -> Token {
// self.py.token()
// self.py
// }
//}
@ -539,12 +547,12 @@ impl<'source, T> ::FromPyObject<'source> for Py<'source, T> where T: PyTypeInfo
impl <'a, T> ToPyObject for Py<'a, T> {
#[inline]
default fn to_object<'p>(&self, py: Token) -> PyPtr<PyObject> {
default fn to_object<'p>(&self, _py: Python) -> PyPtr<PyObject> {
unsafe { PyPtr::from_borrowed_ptr(self.inner) }
}
#[inline]
fn with_borrowed_ptr<F, R>(&self, py: Token, f: F) -> R
fn with_borrowed_ptr<F, R>(&self, _py: Python, f: F) -> R
where F: FnOnce(*mut ffi::PyObject) -> R
{
f(self.inner)
@ -554,12 +562,12 @@ impl <'a, T> ToPyObject for Py<'a, T> {
impl<T> ToPyObject for PyPtr<T> {
#[inline]
default fn to_object(&self, py: Token) -> PyPtr<PyObject> {
default fn to_object(&self, _py: Python) -> PyPtr<PyObject> {
unsafe { PyPtr::from_borrowed_ptr(self.inner) }
}
#[inline]
fn with_borrowed_ptr<F, R>(&self, py: Token, f: F) -> R
fn with_borrowed_ptr<F, R>(&self, _py: Python, f: F) -> R
where F: FnOnce(*mut ffi::PyObject) -> R
{
f(self.inner)
@ -569,7 +577,7 @@ impl<T> ToPyObject for PyPtr<T> {
impl<'p, T> IntoPyObject for Py<'p, T> {
#[inline]
default fn into_object(self, py: Token) -> PyPtr<PyObject> {
default fn into_object(self, _py: Python) -> PyPtr<PyObject> {
let ptr = unsafe { PyPtr::from_owned_ptr(self.inner) };
std::mem::forget(self);
ptr
@ -584,3 +592,10 @@ impl<'p, T> PartialEq for Py<'p, T> {
self.as_ptr() == o.as_ptr()
}
}
impl<'p, T> PartialEq for PyPtr<T> {
#[inline]
fn eq(&self, o: &PyPtr<T>) -> bool {
self.as_ptr() == o.as_ptr()
}
}

View File

@ -28,14 +28,17 @@ use pythonrun::GILGuard;
#[derive(Copy, Clone)]
pub struct Python<'p>(PhantomData<&'p GILGuard>);
#[derive(Copy, Clone)]
pub struct Token<'p>(PhantomData<&'p GILGuard>);
pub struct PythonToken<T>(PhantomData<T>);
impl<T> PythonToken<T> {
pub fn token<'p>(&'p self) -> Python<'p> {
Python(PhantomData)
}
}
pub trait PythonObjectWithToken : Sized {
fn token<'p>(&'p self) -> Token<'p>;
fn token<'p>(&'p self) -> Python<'p>;
}
pub trait PyClone : Sized {
@ -177,7 +180,7 @@ impl<'p> Python<'p> {
unsafe {
let mptr = ffi::PyImport_AddModule("__main__\0".as_ptr() as *const _);
if mptr.is_null() {
return Err(PyErr::fetch(self.token()));
return Err(PyErr::fetch(self));
}
let mdict = ffi::PyModule_GetDict(mptr);
@ -195,47 +198,32 @@ impl<'p> Python<'p> {
let res_ptr = ffi::PyRun_StringFlags(code.as_ptr(),
start, globals, locals, 0 as *mut _);
PyPtr::from_owned_ptr_or_err(self.token(), res_ptr)
PyPtr::from_owned_ptr_or_err(self, res_ptr)
}
}
/// Gets the Python type object for type T.
pub fn get_type<T>(self) -> PyPtr<PyType> where T: PyTypeObject {
T::type_object(self.token())
T::type_object(self)
}
/// Import the Python module with the specified name.
pub fn import(self, name : &str) -> PyResult<Py<'p, PyModule>> {
PyModule::import(self.token(), name)
PyModule::import(self, name)
}
pub fn with_token<T, F>(self, f: F) -> PyPtr<T>
pub fn with_token<T, F>(self, f: F) -> Py<'p, T>
where F: FnOnce(PythonToken<T>) -> T,
T: PyTypeInfo + PyObjectAlloc<Type=T>
{
let value = f(PythonToken(PhantomData));
if let Ok(ob) = Py::new(self.token(), value) {
println!("created: {:?}", &ob as *const _);
ob.into_pptr()
if let Ok(ob) = Py::new(self, value) {
ob
} else {
::err::panic_after_error()
}
}
//}
//impl<'p> PythonObjectWithToken<'p> for Python<'p> {
pub fn token(self) -> Token<'p> {
Token(PhantomData)
}
}
impl<T> PythonToken<T> {
pub fn token(&self) -> Token {
Token(PhantomData)
}
}
impl<'p> Token<'p> {
/// Gets the Python builtin value `None`.
#[allow(non_snake_case)] // the Python keyword starts with uppercase
#[inline]
@ -264,12 +252,6 @@ impl<'p> Token<'p> {
unsafe { PyPtr::from_borrowed_ptr(ffi::Py_NotImplemented()) }
}
/// Gets the Python type object for type T.
#[inline]
pub fn get_type<U>(self) -> PyPtr<PyType> where U: PyTypeObject {
U::type_object(self)
}
/// Execute closure `F` with Python instance.
/// Retrieve Python instance under the assumption that the GIL is already acquired
/// at this point, and stays acquired during closure call.

View File

@ -8,7 +8,7 @@ use std::collections::HashMap;
use {ffi, class};
use err::{PyErr, PyResult};
use pyptr::{Py, PyPtr};
use python::{Python, PythonObjectWithToken, Token};
use python::{Python};
use objects::PyType;
use callback::AbortOnDrop;
use class::methods::PyMethodDefType;
@ -92,12 +92,12 @@ pub trait PyObjectAlloc {
/// and initializes it using init_val.
/// `ty` must be derived from the Self type, and the resulting object
/// must be of type `ty`.
unsafe fn alloc(py: Token, value: Self::Type) -> PyResult<*mut ffi::PyObject>;
unsafe fn alloc(py: Python, value: Self::Type) -> PyResult<*mut ffi::PyObject>;
/// Calls the rust destructor for the object and frees the memory
/// (usually by calling ptr->ob_type->tp_free).
/// This function is used as tp_dealloc implementation.
unsafe fn dealloc(py: Token, obj: *mut ffi::PyObject);
unsafe fn dealloc(py: Python, obj: *mut ffi::PyObject);
}
/// A PythonObject that is usable as a base type for #[class]
@ -108,16 +108,13 @@ impl<T> PyObjectAlloc for T where T : PyTypeInfo {
/// and initializes it using init_val.
/// `ty` must be derived from the Self type, and the resulting object
/// must be of type `ty`.
unsafe fn alloc(py: Token, value: T::Type) -> PyResult<*mut ffi::PyObject> {
unsafe fn alloc(py: Python, value: T::Type) -> PyResult<*mut ffi::PyObject> {
let _ = <T as PyTypeObject>::type_object(py);
let obj = ffi::PyType_GenericAlloc(
<Self as PyTypeInfo>::type_object(), 0);
let offset = <Self as PyTypeInfo>::offset();
println!("alloc {} {:?} {} {}", offset, obj, <Self as PyTypeInfo>::size(),
<Self as PyTypeInfo>::type_object().tp_basicsize);
let ptr = (obj as *mut u8).offset(offset) as *mut Self::Type;
std::ptr::write(ptr, value);
@ -127,7 +124,7 @@ impl<T> PyObjectAlloc for T where T : PyTypeInfo {
/// Calls the rust destructor for the object and frees the memory
/// (usually by calling ptr->ob_type->tp_free).
/// This function is used as tp_dealloc implementation.
unsafe fn dealloc(py: Token, obj: *mut ffi::PyObject) {
unsafe fn dealloc(_py: Python, obj: *mut ffi::PyObject) {
let ptr = (obj as *mut u8).offset(
<Self as PyTypeInfo>::offset() as isize) as *mut Self::Type;
std::ptr::drop_in_place(ptr);
@ -150,14 +147,14 @@ impl<T> PyObjectAlloc for T where T : PyTypeInfo {
pub trait PyTypeObject {
/// Retrieves the type object for this Python object type.
fn type_object(py: Token) -> PyPtr<PyType>;
fn type_object(py: Python) -> PyPtr<PyType>;
}
impl<T> PyTypeObject for T where T: PyObjectAlloc + PyTypeInfo {
#[inline]
fn type_object<'p>(py: Token) -> PyPtr<PyType> {
fn type_object<'p>(py: Python) -> PyPtr<PyType> {
let mut ty = <T as PyTypeInfo>::type_object();
if (ty.tp_flags & ffi::Py_TPFLAGS_READY) != 0 {
@ -172,7 +169,7 @@ impl<T> PyTypeObject for T where T: PyObjectAlloc + PyTypeInfo {
}
}
pub fn initialize_type<'p, T>(py: Token, module_name: Option<&str>, type_name: &str,
pub fn initialize_type<'p, T>(py: Python, module_name: Option<&str>, type_name: &str,
type_object: &mut ffi::PyTypeObject) -> PyResult<PyPtr<PyType>>
where T: PyObjectAlloc + PyTypeInfo
{
@ -302,7 +299,7 @@ unsafe extern "C" fn tp_dealloc_callback<T>(obj: *mut ffi::PyObject)
println!("DEALLOC: {:?}", obj);
let guard = AbortOnDrop("Cannot unwind out of tp_dealloc");
let py = Python::assume_gil_acquired();
let r = <T as PyObjectAlloc>::dealloc(py.token(), obj);
let r = <T as PyObjectAlloc>::dealloc(py, obj);
mem::forget(guard);
r
}

View File

@ -14,7 +14,7 @@ use pyo3::python::ToPythonPointer;
macro_rules! py_run {
($py:expr, $val:ident, $code:expr) => {{
let d = PyDict::new($py);
let d = PyDict::new($py.token());
d.set_item(stringify!($val), &$val).unwrap();
//$py.run($code, None, Some(&d)).map_err(|e| e.print($py)).expect($code);
$py.run($code, None, Some(&d)).expect($code);
@ -27,11 +27,11 @@ macro_rules! py_assert {
macro_rules! py_expect_exception {
($py:expr, $val:ident, $code:expr, $err:ident) => {{
let d = PyDict::new($py);
let d = PyDict::new($py.token());
d.set_item(stringify!($val), &$val).unwrap();
let res = $py.run($code, None, Some(&d));
let err = res.unwrap_err();
if !err.matches($py, $py.get_type::<exc::$err>()) {
if !err.matches($py.token(), $py.token().get_type::<exc::$err>()) {
panic!(format!("Expected {} but got {:?}", stringify!($err), err))
}
}}
@ -46,8 +46,9 @@ fn empty_class() {
let gil = Python::acquire_gil();
let py = gil.python();
let typeobj = py.get_type::<EmptyClass>();
let to = typeobj.as_ref(py.token());
// By default, don't allow creating instances from python.
assert!(typeobj.call(NoArgs, None).is_err());
assert!(to.call(NoArgs, None).is_err());
py_assert!(py, typeobj, "typeobj.__name__ == 'EmptyClass'");
}
@ -59,7 +60,7 @@ struct EmptyClassInModule { }
fn empty_class_in_module() {
let gil = Python::acquire_gil();
let py = gil.python();
let module = PyModule::new(py, "test_module.nested").unwrap();
let module = PyModule::new(py.token(), "test_module.nested").unwrap();
module.add_class::<EmptyClassInModule>().unwrap();
let ty = module.getattr("EmptyClassInModule").unwrap();
@ -83,12 +84,14 @@ fn empty_class_with_new() {
let gil = Python::acquire_gil();
let py = gil.python();
let typeobj = py.get_type::<EmptyClassWithNew>();
assert!(typeobj.call(NoArgs, None).unwrap().cast_into::<EmptyClassWithNew>().is_ok());
let to = typeobj.as_ref(py.token());
assert!(to.call(NoArgs, None).unwrap().cast_into::<EmptyClassWithNew>().is_ok());
}
#[py::class]
struct NewWithOneArg {
_data: i32,
#[token]
token: PythonToken<NewWithOneArg>
}
#[py::methods]
@ -690,7 +693,10 @@ fn unary_arithmetic() {
#[py::class]
struct BinaryArithmetic {token: PythonToken<BinaryArithmetic>}
struct BinaryArithmetic {
#[token]
token: PythonToken<BinaryArithmetic>
}
#[py::proto]
impl PyObjectProtocol for BinaryArithmetic {
@ -796,11 +802,11 @@ impl PyObjectProtocol for RichComparisons2 {
}
fn __richcmp__(&self, py: Python,
other: &PyObject, op: CompareOp) -> PyResult<Py<PyObject>> {
other: &PyObject, op: CompareOp) -> PyResult<PyPtr<PyObject>> {
match op {
CompareOp::Eq => Ok(true.to_object(py).into_object()),
CompareOp::Ne => Ok(false.to_object(py).into_object()),
_ => Ok(py.NotImplemented())
CompareOp::Eq => Ok(true.to_object(py.token()).into_object()),
CompareOp::Ne => Ok(false.to_object(py.token()).into_object()),
_ => Ok(py.token().NotImplemented())
}
}
}