-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(python): Support PyCapsule Interface in DataFrame & Series constructors #17693
Merged
Merged
Changes from 6 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
a0e10be
Support __arrow_c_stream__ in DataFrame constructor
kylebarron 9754fb1
Support stream import to series and use that for DataFrame import
kylebarron d0ea973
Import __arrow_c_array__ as well
kylebarron f4f1162
Merge branch 'main' into kyle/c-stream-import
kylebarron 763e153
reorder pycapsule interface checks
kylebarron 6c4de77
remove pandas not installed check
kylebarron 7446467
Add typing for C Data and Stream protocols
kylebarron b576372
add constructor tests
kylebarron 477ed23
add test cases for empty arrays/streams
kylebarron 1bfb479
Add safety docs
kylebarron 1618d1d
Test for pandas import via pycapsule interface
kylebarron 9fefdeb
merge
ritchie46 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,122 @@ | ||
use polars::export::arrow; | ||
use polars::export::arrow::array::Array; | ||
use polars::export::arrow::ffi; | ||
use polars::export::arrow::ffi::{ | ||
ArrowArray, ArrowArrayStream, ArrowArrayStreamReader, ArrowSchema, | ||
}; | ||
use pyo3::exceptions::{PyTypeError, PyValueError}; | ||
use pyo3::prelude::*; | ||
use pyo3::types::{PyCapsule, PyTuple, PyType}; | ||
|
||
use super::*; | ||
|
||
/// Validate PyCapsule has provided name | ||
fn validate_pycapsule_name(capsule: &Bound<PyCapsule>, expected_name: &str) -> PyResult<()> { | ||
let capsule_name = capsule.name()?; | ||
if let Some(capsule_name) = capsule_name { | ||
let capsule_name = capsule_name.to_str()?; | ||
if capsule_name != expected_name { | ||
return Err(PyValueError::new_err(format!( | ||
"Expected name '{}' in PyCapsule, instead got '{}'", | ||
expected_name, capsule_name | ||
))); | ||
} | ||
} else { | ||
return Err(PyValueError::new_err( | ||
"Expected schema PyCapsule to have name set.", | ||
)); | ||
} | ||
|
||
Ok(()) | ||
} | ||
|
||
/// Import `__arrow_c_array__` across Python boundary | ||
pub(crate) fn call_arrow_c_array<'py>( | ||
ob: &'py Bound<PyAny>, | ||
) -> PyResult<(Bound<'py, PyCapsule>, Bound<'py, PyCapsule>)> { | ||
if !ob.hasattr("__arrow_c_array__")? { | ||
return Err(PyValueError::new_err( | ||
"Expected an object with dunder __arrow_c_array__", | ||
)); | ||
} | ||
|
||
let tuple = ob.getattr("__arrow_c_array__")?.call0()?; | ||
if !tuple.is_instance_of::<PyTuple>() { | ||
return Err(PyTypeError::new_err( | ||
"Expected __arrow_c_array__ to return a tuple.", | ||
)); | ||
} | ||
|
||
let schema_capsule = tuple.get_item(0)?.downcast_into()?; | ||
let array_capsule = tuple.get_item(1)?.downcast_into()?; | ||
Ok((schema_capsule, array_capsule)) | ||
} | ||
|
||
pub(crate) fn import_array_pycapsules( | ||
schema_capsule: &Bound<PyCapsule>, | ||
array_capsule: &Bound<PyCapsule>, | ||
) -> PyResult<(arrow::datatypes::Field, Box<dyn Array>)> { | ||
validate_pycapsule_name(schema_capsule, "arrow_schema")?; | ||
validate_pycapsule_name(array_capsule, "arrow_array")?; | ||
|
||
let schema_ptr = unsafe { schema_capsule.reference::<ArrowSchema>() }; | ||
let array_ptr = unsafe { std::ptr::replace(array_capsule.pointer() as _, ArrowArray::empty()) }; | ||
|
||
let (field, array) = unsafe { | ||
kylebarron marked this conversation as resolved.
Show resolved
Hide resolved
|
||
let field = ffi::import_field_from_c(schema_ptr).unwrap(); | ||
let array = ffi::import_array_from_c(array_ptr, field.data_type().clone()).unwrap(); | ||
(field, array) | ||
}; | ||
|
||
Ok((field, array)) | ||
} | ||
|
||
/// Import `__arrow_c_stream__` across Python boundary. | ||
fn call_arrow_c_stream<'py>(ob: &'py Bound<PyAny>) -> PyResult<Bound<'py, PyCapsule>> { | ||
if !ob.hasattr("__arrow_c_stream__")? { | ||
return Err(PyValueError::new_err( | ||
"Expected an object with dunder __arrow_c_stream__", | ||
)); | ||
} | ||
|
||
let capsule = ob.getattr("__arrow_c_stream__")?.call0()?.downcast_into()?; | ||
Ok(capsule) | ||
} | ||
|
||
pub(crate) fn import_stream_pycapsule(capsule: &Bound<PyCapsule>) -> PyResult<PySeries> { | ||
validate_pycapsule_name(capsule, "arrow_array_stream")?; | ||
|
||
// Takes ownership of the pointed to ArrowArrayStream | ||
// This acts to move the data out of the capsule pointer, setting the release callback to NULL | ||
let stream_ptr = | ||
Box::new(unsafe { std::ptr::replace(capsule.pointer() as _, ArrowArrayStream::empty()) }); | ||
|
||
let mut stream = unsafe { | ||
ArrowArrayStreamReader::try_new(stream_ptr) | ||
.map_err(|err| PyValueError::new_err(err.to_string()))? | ||
}; | ||
|
||
let mut produced_arrays: Vec<Box<dyn Array>> = vec![]; | ||
while let Some(array) = unsafe { stream.next() } { | ||
produced_arrays.push(array.unwrap()); | ||
} | ||
|
||
let s = Series::try_from((stream.field(), produced_arrays)).unwrap(); | ||
Ok(PySeries::new(s)) | ||
} | ||
#[pymethods] | ||
impl PySeries { | ||
#[classmethod] | ||
pub fn from_arrow_c_array(_cls: &Bound<PyType>, ob: &Bound<'_, PyAny>) -> PyResult<Self> { | ||
let (schema_capsule, array_capsule) = call_arrow_c_array(ob)?; | ||
let (field, array) = import_array_pycapsules(&schema_capsule, &array_capsule)?; | ||
let s = Series::try_from((&field, array)).unwrap(); | ||
Ok(PySeries::new(s)) | ||
} | ||
|
||
#[classmethod] | ||
pub fn from_arrow_c_stream(_cls: &Bound<PyType>, ob: &Bound<'_, PyAny>) -> PyResult<Self> { | ||
let capsule = call_arrow_c_stream(ob)?; | ||
import_stream_pycapsule(&capsule) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you add a
// SAFETY
comment explaining which invariants must hold here?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Take a look and see if those safety comments are ok