Skip to content

Commit

Permalink
upgrading to pyo3 0.23
Browse files Browse the repository at this point in the history
  • Loading branch information
proycon committed Nov 18, 2024
1 parent 155b7c1 commit e36c8e1
Show file tree
Hide file tree
Showing 11 changed files with 153 additions and 111 deletions.
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ name = "stam"
crate-type = ["cdylib"]

[dependencies]
pyo3 = { version = "0.22.3", features = ["chrono"] }
pyo3 = { version = "0.23.1", features = ["chrono"] }
rayon = "1.10.0"
stam = "0.16.4"
stam-tools = "0.9.1"
stam = "0.16.5"
stam-tools = "0.9.2"

[features]
default = ["pyo3/extension-module"]
Expand Down
18 changes: 11 additions & 7 deletions src/annotation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use pyo3::exceptions::{PyIndexError, PyRuntimeError};
use pyo3::prelude::*;
use pyo3::pyclass::CompareOp;
use pyo3::types::*;
use pyo3::IntoPyObject;
use std::borrow::Cow;
use std::ops::FnOnce;
use std::sync::{Arc, RwLock};
Expand Down Expand Up @@ -47,7 +48,10 @@ impl PyAnnotation {
store: Arc<RwLock<AnnotationStore>>,
py: Python<'py>,
) -> Bound<'py, PyAny> {
Self::new(handle, store).into_py(py).into_bound(py)
Self::new(handle, store)
.into_pyobject(py)
.expect("infallible")
.into_any()
}
}

Expand Down Expand Up @@ -124,7 +128,7 @@ impl PyAnnotation {
///
/// If you are sure an annotation only references a single contingent text slice or are okay with slices being concatenated, then you can use `str()` instead.
fn text<'py>(&self, py: Python<'py>) -> Bound<'py, PyList> {
let list = PyList::empty_bound(py);
let list = PyList::empty(py);
self.map(|annotation| {
for text in annotation.text() {
list.append(text).ok();
Expand Down Expand Up @@ -302,7 +306,7 @@ impl PyAnnotation {
/// Returns a list of resources this annotation refers to
#[pyo3(signature = (limit=None))]
fn resources<'py>(&self, limit: Option<usize>, py: Python<'py>) -> Bound<'py, PyList> {
let list = PyList::empty_bound(py);
let list = PyList::empty(py);
self.map(|annotation| {
for (i, resource) in annotation.resources().enumerate() {
list.append(PyTextResource::new_py(
Expand All @@ -324,7 +328,7 @@ impl PyAnnotation {
/// Returns the resources this annotation refers to (as metadata) in a list
#[pyo3(signature = (limit=None))]
fn datasets<'py>(&self, limit: Option<usize>, py: Python<'py>) -> Bound<'py, PyList> {
let list = PyList::empty_bound(py);
let list = PyList::empty(py);
self.map(|annotation| {
for (i, dataset) in annotation.datasets().enumerate() {
list.append(PyAnnotationDataSet::new_py(
Expand Down Expand Up @@ -579,7 +583,7 @@ impl PyAnnotation {
py: Python<'py>,
kwargs: Option<Bound<'py, PyDict>>,
) -> PyResult<Bound<'py, PyList>> {
let alignments = PyList::empty_bound(py);
let alignments = PyList::empty(py);
let storeclone = self.store.clone();
let mut annotations = false;
if let Some(kwargs) = kwargs {
Expand All @@ -594,7 +598,7 @@ impl PyAnnotation {
if let (Some(left), Some(right)) = (annoiter.next(), annoiter.next()) {
//complex transposition
for (text1, text2) in left.textselections().zip(right.textselections()) {
let alignment = PyList::empty_bound(py);
let alignment = PyList::empty(py);
if annotations {
alignment
.append(PyAnnotation::new_py(left.handle(), storeclone.clone(), py))
Expand All @@ -618,7 +622,7 @@ impl PyAnnotation {
//simple transposition
let mut textiter = annotation.textselections();
if let (Some(text1), Some(text2)) = (textiter.next(), textiter.next()) {
let alignment = PyList::empty_bound(py);
let alignment = PyList::empty(py);
alignment
.append(PyTextSelection::from_result_to_py(text1, &storeclone, py))
.map_err(|_| StamError::OtherError("failed to extract alignment"))?;
Expand Down
69 changes: 47 additions & 22 deletions src/annotationdata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,18 @@ impl PyDataKey {
) -> PyDataKey {
PyDataKey { set, handle, store }
}

pub(crate) fn new_py<'py>(
handle: DataKeyHandle,
set: AnnotationDataSetHandle,
store: Arc<RwLock<AnnotationStore>>,
py: Python<'py>,
) -> Bound<'py, PyAny> {
Self::new(handle, set, store)
.into_pyobject(py)
.expect("infallible")
.into_any()
}
}

#[pymethods]
Expand All @@ -54,12 +66,11 @@ impl PyDataKey {
self.map(|datakey| Ok(datakey.id() == Some(other)))
}

fn __richcmp__(&self, other: PyRef<Self>, op: CompareOp) -> Py<PyAny> {
let py = other.py();
fn __richcmp__(&self, other: PyRef<Self>, op: CompareOp) -> bool {
match op {
CompareOp::Eq => (self.set == other.set && self.handle == other.handle).into_py(py),
CompareOp::Ne => (self.set != other.set || self.handle != other.handle).into_py(py),
_ => py.NotImplemented(),
CompareOp::Eq => self.set == other.set && self.handle == other.handle,
CompareOp::Ne => self.set != other.set || self.handle != other.handle,
_ => false,
}
}

Expand Down Expand Up @@ -252,6 +263,18 @@ impl PyAnnotationData {
) -> PyAnnotationData {
PyAnnotationData { set, handle, store }
}

pub(crate) fn new_py<'py>(
handle: AnnotationDataHandle,
set: AnnotationDataSetHandle,
store: Arc<RwLock<AnnotationStore>>,
py: Python<'py>,
) -> Bound<'py, PyAny> {
Self::new(handle, set, store)
.into_pyobject(py)
.expect("infallible")
.into_any()
}
}

pub(crate) fn datavalue_from_py<'py>(value: Bound<'py, PyAny>) -> Result<DataValue, StamError> {
Expand Down Expand Up @@ -288,18 +311,22 @@ pub(crate) fn datavalue_into_py<'py>(
py: Python<'py>,
) -> Result<Bound<'py, PyAny>, StamError> {
match datavalue {
DataValue::String(s) => Ok(s.into_py(py).into_bound(py)),
DataValue::Float(f) => Ok(f.into_py(py).into_bound(py)),
DataValue::Int(v) => Ok(v.into_py(py).into_bound(py)),
DataValue::Bool(v) => Ok(v.into_py(py).into_bound(py)),
DataValue::Datetime(v) => Ok(v.into_py(py).into_bound(py)),
DataValue::String(s) => Ok(s.into_pyobject(py).expect("infallible").into_any()),
DataValue::Float(f) => Ok(f.into_pyobject(py).expect("infallible").into_any()),
DataValue::Int(v) => Ok(v.into_pyobject(py).expect("infallible").into_any()),
DataValue::Bool(v) => Ok(<pyo3::Bound<'_, pyo3::types::PyBool> as Clone>::clone(
//ugly, compiler suggested this! doesn't work without for pyo3 0.23
&v.into_pyobject(py).expect("infallible"),
)
.into_any()),
DataValue::Datetime(v) => Ok(v.into_pyobject(py).expect("infallible").into_any()),
DataValue::Null => {
//feels a bit hacky, but I can't find a PyNone to return as PyAny
let x: Option<bool> = None;
Ok(x.into_py(py).into_bound(py))
Ok(x.into_pyobject(py).expect("infallible").into_any())
}
DataValue::List(v) => {
let pylist = PyList::empty_bound(py);
let pylist = PyList::empty(py);
for item in v.iter() {
let pyvalue = datavalue_into_py(item, py)?;
pylist.append(pyvalue).expect("adding value to list");
Expand Down Expand Up @@ -337,12 +364,11 @@ impl PyDataValue {
})
}

fn __richcmp__(&self, other: PyRef<Self>, op: CompareOp) -> Py<PyAny> {
let py = other.py();
fn __richcmp__(&self, other: PyRef<Self>, op: CompareOp) -> bool {
match op {
CompareOp::Eq => (self.value == other.value).into_py(py),
CompareOp::Ne => (self.value != other.value).into_py(py),
_ => py.NotImplemented(),
CompareOp::Eq => self.value == other.value,
CompareOp::Ne => self.value != other.value,
_ => false,
}
}

Expand Down Expand Up @@ -446,12 +472,11 @@ impl PyAnnotationData {
self.map(|annotationdata| Ok(annotationdata.id() == Some(other)))
}

fn __richcmp__(&self, other: PyRef<Self>, op: CompareOp) -> Py<PyAny> {
let py = other.py();
fn __richcmp__(&self, other: PyRef<Self>, op: CompareOp) -> bool {
match op {
CompareOp::Eq => (self.set == other.set && self.handle == other.handle).into_py(py),
CompareOp::Ne => (self.set != other.set || self.handle != other.handle).into_py(py),
_ => py.NotImplemented(),
CompareOp::Eq => self.set == other.set && self.handle == other.handle,
CompareOp::Ne => self.set != other.set || self.handle != other.handle,
_ => false,
}
}

Expand Down
5 changes: 4 additions & 1 deletion src/annotationdataset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ impl PyAnnotationDataSet {
store: Arc<RwLock<AnnotationStore>>,
py: Python<'py>,
) -> Bound<'py, PyAny> {
Self::new(handle, store).into_py(py).into_bound(py)
Self::new(handle, store)
.into_pyobject(py)
.expect("infallible")
.into_any()
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/annotationstore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ impl PyAnnotationStore {
#[pyo3(text_signature = "(self, id=None, file=None, string=None, config=None)")]
fn new<'py>(kwargs: Option<Bound<'py, PyDict>>, py: Python<'py>) -> PyResult<Self> {
if let Some(kwargs) = kwargs {
let mut config = PyDict::new_bound(py);
let mut config = PyDict::new(py);
for (key, value) in kwargs.iter() {
match key.downcast()?.extract()? {
"config" => {
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const VERSION: &'static str = env!("CARGO_PKG_VERSION");

#[pymodule]
fn stam(py: Python<'_>, m: Bound<'_, PyModule>) -> PyResult<()> {
m.add("StamError", py.get_type_bound::<PyStamError>())?;
m.add("StamError", py.get_type::<PyStamError>())?;
m.add("VERSION", VERSION)?;
m.add_class::<PyAnnotationStore>()?;
m.add_class::<PyAnnotationDataSet>()?;
Expand Down
40 changes: 16 additions & 24 deletions src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -500,9 +500,9 @@ pub(crate) fn query_to_python<'py>(
store: Arc<RwLock<AnnotationStore>>,
py: Python<'py>,
) -> Result<Bound<'py, PyList>, StamError> {
let results = PyList::empty_bound(py);
let results = PyList::empty(py);
for resultitems in iter {
let dict = PyDict::new_bound(py);
let dict = PyDict::new(py);
for (result, name) in resultitems.iter().zip(resultitems.names()) {
if name.is_none() {
continue;
Expand All @@ -512,70 +512,62 @@ pub(crate) fn query_to_python<'py>(
QueryResultItem::Annotation(annotation) => {
dict.set_item(
name,
PyAnnotation::new(annotation.handle(), store.clone())
.into_py(py)
.into_bound(py),
PyAnnotation::new_py(annotation.handle(), store.clone(), py),
)
.unwrap();
}
QueryResultItem::AnnotationData(data) => {
dict.set_item(
name,
PyAnnotationData::new(data.handle(), data.set().handle(), store.clone())
.into_py(py)
.into_bound(py),
PyAnnotationData::new_py(
data.handle(),
data.set().handle(),
store.clone(),
py,
),
)
.unwrap();
}
QueryResultItem::DataKey(key) => {
dict.set_item(
name,
PyDataKey::new(key.handle(), key.set().handle(), store.clone())
.into_py(py)
.into_bound(py),
PyDataKey::new_py(key.handle(), key.set().handle(), store.clone(), py),
)
.unwrap();
}
QueryResultItem::TextResource(resource) => {
dict.set_item(
name,
PyTextResource::new(resource.handle(), store.clone())
.into_py(py)
.into_bound(py),
PyTextResource::new_py(resource.handle(), store.clone(), py),
)
.unwrap();
}
QueryResultItem::AnnotationDataSet(dataset) => {
dict.set_item(
name,
PyAnnotationDataSet::new(dataset.handle(), store.clone())
.into_py(py)
.into_bound(py),
PyAnnotationDataSet::new_py(dataset.handle(), store.clone(), py),
)
.unwrap();
}
QueryResultItem::TextSelection(textselection) => {
dict.set_item(
name,
PyTextSelection::new(
PyTextSelection::new_py(
textselection
.as_ref()
.expect("textselection must be bound")
.clone(),
textselection.resource().handle(),
store.clone(),
)
.into_py(py)
.into_bound(py),
py,
),
)
.unwrap();
}
QueryResultItem::AnnotationSubStore(substore) => {
dict.set_item(
name,
PyAnnotationSubStore::new(substore.handle(), store.clone())
.into_py(py)
.into_bound(py),
PyAnnotationSubStore::new_py(substore.handle(), store.clone(), py),
)
.unwrap();
}
Expand Down
Loading

0 comments on commit e36c8e1

Please sign in to comment.