1use std::convert::{From, TryFrom};
67use std::ffi::CStr;
68use std::ptr::NonNull;
69use std::sync::Arc;
70
71use arrow_array::ffi;
72use arrow_array::ffi::{FFI_ArrowArray, FFI_ArrowSchema};
73use arrow_array::ffi_stream::{FFI_ArrowArrayStream, RecordBatchStreamReader};
74use arrow_array::{
75 RecordBatch, RecordBatchIterator, RecordBatchOptions, RecordBatchReader, StructArray,
76 make_array,
77};
78use arrow_data::ArrayData;
79use arrow_schema::{ArrowError, DataType, Field, Schema, SchemaRef};
80use pyo3::exceptions::{PyMemoryError, PyTypeError, PyValueError};
81use pyo3::ffi::Py_uintptr_t;
82use pyo3::prelude::*;
83use pyo3::sync::PyOnceLock;
84use pyo3::types::{PyCapsule, PyDict, PyList, PyString, PyType};
85use pyo3::{CastError, import_exception, intern};
86#[cfg(feature = "experimental-inspect")]
87use pyo3::{
88 inspect::PyStaticExpr, type_hint_identifier, type_hint_subscript, type_hint_union,
89 type_object::PyTypeInfo,
90};
91
92macro_rules! type_hint {
95 ($name:ident = $hint:expr) => {
96 #[cfg(feature = "experimental-inspect")]
97 const $name: PyStaticExpr = $hint;
98 };
99}
100
101import_exception!(pyarrow, ArrowException);
102pub type PyArrowException = ArrowException;
104
105fn to_py_err(err: ArrowError) -> PyErr {
106 PyArrowException::new_err(err.to_string())
107}
108
109#[cfg(feature = "experimental-inspect")]
117const ARRAY_STREAM_INPUT_TYPE: PyStaticExpr = type_hint_union!(
118 type_hint_identifier!("pyarrow", "RecordBatchReader"),
119 type_hint_identifier!("pyarrow", "Table")
120);
121
122pub trait FromPyArrowUnchecked: Sized {
126 unsafe fn from_pyarrow_bound_unchecked(value: &Bound<PyAny>) -> PyResult<Self>;
133}
134
135pub trait FromPyArrow: Sized {
137 #[cfg(feature = "experimental-inspect")]
149 const INPUT_TYPE: PyStaticExpr = type_hint_identifier!("_typeshed", "Incomplete");
150
151 fn from_pyarrow_bound(value: &Bound<PyAny>) -> PyResult<Self>;
155}
156
157pub trait ToPyArrow {
159 #[cfg(feature = "experimental-inspect")]
164 const OUTPUT_TYPE: PyStaticExpr = type_hint_identifier!("_typeshed", "Incomplete");
165
166 fn to_pyarrow<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>>;
168}
169
170pub trait IntoPyArrow {
172 #[cfg(feature = "experimental-inspect")]
176 const OUTPUT_TYPE: PyStaticExpr = type_hint_identifier!("_typeshed", "Incomplete");
177
178 fn into_pyarrow(self, py: Python<'_>) -> PyResult<Bound<'_, PyAny>>;
180}
181
182impl<T: ToPyArrow> IntoPyArrow for T {
183 type_hint!(OUTPUT_TYPE = <T as ToPyArrow>::OUTPUT_TYPE);
184
185 fn into_pyarrow(self, py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
186 self.to_pyarrow(py)
187 }
188}
189
190fn validate_class(expected: &Bound<PyType>, value: &Bound<PyAny>) -> PyResult<()> {
191 if !value.is_instance(expected)? {
192 return Err(PyTypeError::new_err(format!(
193 "Expected instance of {}, got {}",
194 expected.fully_qualified_name()?,
195 value.get_type().fully_qualified_name()?
196 )));
197 }
198 Ok(())
199}
200
201impl FromPyArrow for DataType {
202 type_hint!(INPUT_TYPE = type_hint_identifier!("pyarrow", "DataType"));
203
204 fn from_pyarrow_bound(value: &Bound<PyAny>) -> PyResult<Self> {
205 if let Some(capsule) =
209 call_capsule_method_if_exists(value, intern!(value.py(), "__arrow_c_schema__"))?
210 {
211 let schema_ptr = extract_capsule::<FFI_ArrowSchema>(
212 &capsule,
213 c"arrow_schema",
214 "__arrow_c_schema__",
215 )?;
216 return unsafe { DataType::try_from(schema_ptr.as_ref()) }.map_err(to_py_err);
217 }
218
219 validate_class(data_type_class(value.py())?, value)?;
220
221 let mut c_schema = FFI_ArrowSchema::empty();
222 value.call_method1(
223 intern!(value.py(), "_export_to_c"),
224 (&raw mut c_schema as Py_uintptr_t,),
225 )?;
226 DataType::try_from(&c_schema).map_err(to_py_err)
227 }
228}
229
230impl ToPyArrow for DataType {
231 type_hint!(OUTPUT_TYPE = type_hint_identifier!("pyarrow", "DataType"));
232
233 fn to_pyarrow<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
234 let c_schema = FFI_ArrowSchema::try_from(self).map_err(to_py_err)?;
235 data_type_class(py)?.call_method1(
236 intern!(py, "_import_from_c"),
237 (&raw const c_schema as Py_uintptr_t,),
238 )
239 }
240}
241
242impl FromPyArrow for Field {
243 type_hint!(INPUT_TYPE = type_hint_identifier!("pyarrow", "Field"));
244
245 fn from_pyarrow_bound(value: &Bound<PyAny>) -> PyResult<Self> {
246 if let Some(capsule) =
250 call_capsule_method_if_exists(value, intern!(value.py(), "__arrow_c_schema__"))?
251 {
252 let schema_ptr = extract_capsule::<FFI_ArrowSchema>(
253 &capsule,
254 c"arrow_schema",
255 "__arrow_c_schema__",
256 )?;
257 return unsafe { Field::try_from(schema_ptr.as_ref()) }.map_err(to_py_err);
258 }
259
260 validate_class(field_class(value.py())?, value)?;
261
262 let mut c_schema = FFI_ArrowSchema::empty();
263 value.call_method1(
264 intern!(value.py(), "_export_to_c"),
265 (&raw mut c_schema as Py_uintptr_t,),
266 )?;
267 Field::try_from(&c_schema).map_err(to_py_err)
268 }
269}
270
271impl ToPyArrow for Field {
272 type_hint!(OUTPUT_TYPE = type_hint_identifier!("pyarrow", "Field"));
273
274 fn to_pyarrow<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
275 let c_schema = FFI_ArrowSchema::try_from(self).map_err(to_py_err)?;
276 field_class(py)?.call_method1(
277 intern!(py, "_import_from_c"),
278 (&raw const c_schema as Py_uintptr_t,),
279 )
280 }
281}
282
283impl FromPyArrow for Schema {
284 type_hint!(INPUT_TYPE = type_hint_identifier!("pyarrow", "Schema"));
285
286 fn from_pyarrow_bound(value: &Bound<PyAny>) -> PyResult<Self> {
287 if let Some(capsule) =
291 call_capsule_method_if_exists(value, intern!(value.py(), "__arrow_c_schema__"))?
292 {
293 let schema_ptr = extract_capsule::<FFI_ArrowSchema>(
294 &capsule,
295 c"arrow_schema",
296 "__arrow_c_schema__",
297 )?;
298 return unsafe { Schema::try_from(schema_ptr.as_ref()) }.map_err(to_py_err);
299 }
300
301 validate_class(schema_class(value.py())?, value)?;
302
303 let mut c_schema = FFI_ArrowSchema::empty();
304 value.call_method1(
305 intern!(value.py(), "_export_to_c"),
306 (&raw mut c_schema as Py_uintptr_t,),
307 )?;
308 Schema::try_from(&c_schema).map_err(to_py_err)
309 }
310}
311
312impl ToPyArrow for Schema {
313 type_hint!(OUTPUT_TYPE = type_hint_identifier!("pyarrow", "Schema"));
314
315 fn to_pyarrow<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
316 let c_schema = FFI_ArrowSchema::try_from(self).map_err(to_py_err)?;
317 schema_class(py)?.call_method1(
318 intern!(py, "_import_from_c"),
319 (&raw const c_schema as Py_uintptr_t,),
320 )
321 }
322}
323
324impl FromPyArrowUnchecked for ArrayData {
325 unsafe fn from_pyarrow_bound_unchecked(value: &Bound<PyAny>) -> PyResult<Self> {
326 if let Some((schema_capsule, array_capsule)) = call_arrow_c_array_method_if_exists(value)? {
330 let schema_ptr =
331 extract_capsule(&schema_capsule, c"arrow_schema", "__arrow_c_array__")?;
332 let array_ptr = extract_capsule(&array_capsule, c"arrow_array", "__arrow_c_array__")?;
333 let array = unsafe { FFI_ArrowArray::from_raw(array_ptr.as_ptr()) };
334 return unsafe { ffi::from_ffi(array, schema_ptr.as_ref()) }.map_err(to_py_err);
335 }
336
337 validate_class(array_class(value.py())?, value)?;
338
339 let mut array = FFI_ArrowArray::empty();
341 let mut schema = FFI_ArrowSchema::empty();
342
343 value.call_method1(
347 intern!(value.py(), "_export_to_c"),
348 (
349 &raw mut array as Py_uintptr_t,
350 &raw mut schema as Py_uintptr_t,
351 ),
352 )?;
353
354 unsafe { ffi::from_ffi(array, &schema) }.map_err(to_py_err)
355 }
356}
357
358impl FromPyArrow for ArrayData {
359 type_hint!(INPUT_TYPE = type_hint_identifier!("pyarrow", "Array"));
360
361 fn from_pyarrow_bound(value: &Bound<PyAny>) -> PyResult<Self> {
362 let data = unsafe { ArrayData::from_pyarrow_bound_unchecked(value)? };
363 data.validate_full().map_err(to_py_err)?;
364 Ok(data)
365 }
366}
367
368impl ToPyArrow for ArrayData {
369 type_hint!(OUTPUT_TYPE = type_hint_identifier!("pyarrow", "Array"));
370
371 fn to_pyarrow<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
372 let array = FFI_ArrowArray::new(self);
373 let schema = FFI_ArrowSchema::try_from(self.data_type()).map_err(to_py_err)?;
374 array_class(py)?.call_method1(
375 intern!(py, "_import_from_c"),
376 (
377 &raw const array as Py_uintptr_t,
378 &raw const schema as Py_uintptr_t,
379 ),
380 )
381 }
382}
383
384impl<T: FromPyArrow> FromPyArrow for Vec<T> {
385 type_hint!(
386 INPUT_TYPE = type_hint_subscript!(
387 type_hint_identifier!("collections.abc", "Iterable"),
388 <T as FromPyArrow>::INPUT_TYPE
389 )
390 );
391
392 fn from_pyarrow_bound(value: &Bound<PyAny>) -> PyResult<Self> {
393 let mut v = Vec::new();
394 if let Ok(len) = value.len() {
395 v.try_reserve(len)
396 .map_err(|e| PyMemoryError::new_err(e.to_string()))?;
397 }
398 for item in value.try_iter()? {
399 v.push(T::from_pyarrow_bound(&item?)?);
400 }
401 Ok(v)
402 }
403}
404
405impl<T: ToPyArrow> ToPyArrow for Vec<T> {
406 type_hint!(
407 OUTPUT_TYPE = type_hint_subscript!(PyList::TYPE_HINT, <T as ToPyArrow>::OUTPUT_TYPE)
408 );
409
410 fn to_pyarrow<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
411 self.iter()
412 .map(|v| v.to_pyarrow(py))
413 .collect::<PyResult<Vec<_>>>()?
414 .into_pyobject(py)
415 }
416}
417
418fn record_batch_from_pyarrow_bound_impl(
419 value: &Bound<PyAny>,
420 validate: bool,
421) -> PyResult<RecordBatch> {
422 if let Some((schema_capsule, array_capsule)) = call_arrow_c_array_method_if_exists(value)? {
426 let schema_ptr = extract_capsule(&schema_capsule, c"arrow_schema", "__arrow_c_array__")?;
427 let array_ptr = extract_capsule(&array_capsule, c"arrow_array", "__arrow_c_array__")?;
428 let ffi_array = unsafe { FFI_ArrowArray::from_raw(array_ptr.as_ptr()) };
429 let array_data =
430 unsafe { ffi::from_ffi(ffi_array, schema_ptr.as_ref()) }.map_err(to_py_err)?;
431 if validate {
432 array_data.validate_full().map_err(to_py_err)?;
433 }
434 if !matches!(array_data.data_type(), DataType::Struct(_)) {
435 return Err(PyTypeError::new_err(format!(
436 "Expected Struct type from __arrow_c_array__, found {}.",
437 array_data.data_type()
438 )));
439 }
440 let options = RecordBatchOptions::default().with_row_count(Some(array_data.len()));
441 let array = StructArray::from(array_data);
442 let schema = unsafe { Arc::new(Schema::try_from(schema_ptr.as_ref()).map_err(to_py_err)?) };
445 let (_fields, columns, nulls) = array.into_parts();
446 if nulls.map(|n| n.null_count()).unwrap_or_default() != 0 {
447 return Err(PyValueError::new_err(
448 "Cannot convert nullable StructArray to RecordBatch, see StructArray documentation",
449 ));
450 }
451 return RecordBatch::try_new_with_options(schema, columns, &options).map_err(to_py_err);
452 }
453
454 validate_class(record_batch_class(value.py())?, value)?;
455 let schema = value.getattr("schema")?;
457 let schema = Arc::new(Schema::from_pyarrow_bound(&schema)?);
458
459 let arrays = value.getattr("columns")?;
460 let arrays = arrays
461 .cast::<PyList>()?
462 .iter()
463 .map(|a| {
464 let data = unsafe { ArrayData::from_pyarrow_bound_unchecked(&a)? };
465 if validate {
466 data.validate_full().map_err(to_py_err)?;
467 }
468 Ok(make_array(data))
469 })
470 .collect::<PyResult<_>>()?;
471
472 let row_count = value
473 .getattr("num_rows")
474 .ok()
475 .and_then(|x| x.extract().ok());
476 let options = RecordBatchOptions::default().with_row_count(row_count);
477
478 RecordBatch::try_new_with_options(schema, arrays, &options).map_err(to_py_err)
479}
480
481impl FromPyArrow for RecordBatch {
482 type_hint!(INPUT_TYPE = type_hint_identifier!("pyarrow", "RecordBatch"));
483
484 fn from_pyarrow_bound(value: &Bound<PyAny>) -> PyResult<Self> {
485 record_batch_from_pyarrow_bound_impl(value, true)
486 }
487}
488
489impl FromPyArrowUnchecked for RecordBatch {
490 unsafe fn from_pyarrow_bound_unchecked(value: &Bound<PyAny>) -> PyResult<Self> {
491 record_batch_from_pyarrow_bound_impl(value, false)
492 }
493}
494
495impl ToPyArrow for RecordBatch {
496 type_hint!(OUTPUT_TYPE = type_hint_identifier!("pyarrow", "RecordBatch"));
497
498 fn to_pyarrow<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
499 let reader = RecordBatchIterator::new(vec![Ok(self.clone())], self.schema());
501 let reader: Box<dyn RecordBatchReader + Send> = Box::new(reader);
502 let py_reader = reader.into_pyarrow(py)?;
503 py_reader.call_method0(intern!(py, "read_next_batch"))
504 }
505}
506
507impl FromPyArrow for RecordBatchStreamReader {
509 type_hint!(INPUT_TYPE = ARRAY_STREAM_INPUT_TYPE);
510
511 fn from_pyarrow_bound(value: &Bound<PyAny>) -> PyResult<Self> {
512 if let Some(capsule) =
516 call_capsule_method_if_exists(value, intern!(value.py(), "__arrow_c_stream__"))?
517 {
518 let stream_ptr =
519 extract_capsule(&capsule, c"arrow_array_stream", "__arrow_c_stream__")?;
520 let stream = unsafe { FFI_ArrowArrayStream::from_raw(stream_ptr.as_ptr()) };
521
522 let stream_reader = RecordBatchStreamReader::try_new(stream)
523 .map_err(|err| PyValueError::new_err(err.to_string()))?;
524
525 return Ok(stream_reader);
526 }
527
528 validate_class(record_batch_reader_class(value.py())?, value)?;
529
530 let mut stream = FFI_ArrowArrayStream::empty();
532
533 value.call_method1(
537 intern!(value.py(), "_export_to_c"),
538 (&raw mut stream as Py_uintptr_t,),
539 )?;
540
541 RecordBatchStreamReader::try_new(stream)
542 .map_err(|err| PyValueError::new_err(err.to_string()))
543 }
544}
545
546impl IntoPyArrow for Box<dyn RecordBatchReader + Send> {
548 type_hint!(OUTPUT_TYPE = type_hint_identifier!("pyarrow", "RecordBatchReader"));
549
550 fn into_pyarrow(self, py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
553 let stream = FFI_ArrowArrayStream::new(self);
554 record_batch_reader_class(py)?.call_method1(
555 intern!(py, "_import_from_c"),
556 (&raw const stream as Py_uintptr_t,),
557 )
558 }
559}
560
561impl IntoPyArrow for RecordBatchStreamReader {
563 type_hint!(OUTPUT_TYPE = type_hint_identifier!("pyarrow", "RecordBatchReader"));
564
565 fn into_pyarrow(self, py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
566 let boxed: Box<dyn RecordBatchReader + Send> = Box::new(self);
567 boxed.into_pyarrow(py)
568 }
569}
570
571#[derive(Clone)]
589pub struct Table {
590 record_batches: Vec<RecordBatch>,
591 schema: SchemaRef,
592}
593
594impl Table {
595 pub fn try_new(
596 record_batches: Vec<RecordBatch>,
597 schema: SchemaRef,
598 ) -> Result<Self, ArrowError> {
599 for record_batch in &record_batches {
600 if schema != record_batch.schema() {
601 return Err(ArrowError::SchemaError(format!(
602 "All record batches must have the same schema. \
603 Expected schema: {:?}, got schema: {:?}",
604 schema,
605 record_batch.schema()
606 )));
607 }
608 }
609 Ok(Self {
610 record_batches,
611 schema,
612 })
613 }
614
615 pub fn record_batches(&self) -> &[RecordBatch] {
616 &self.record_batches
617 }
618
619 pub fn schema(&self) -> SchemaRef {
620 self.schema.clone()
621 }
622
623 pub fn into_inner(self) -> (Vec<RecordBatch>, SchemaRef) {
624 (self.record_batches, self.schema)
625 }
626}
627
628impl TryFrom<Box<dyn RecordBatchReader>> for Table {
629 type Error = ArrowError;
630
631 fn try_from(value: Box<dyn RecordBatchReader>) -> Result<Self, ArrowError> {
632 let schema = value.schema();
633 let batches = value.collect::<Result<Vec<_>, _>>()?;
634 Self::try_new(batches, schema)
635 }
636}
637
638impl FromPyArrow for Table {
640 type_hint!(INPUT_TYPE = ARRAY_STREAM_INPUT_TYPE);
641
642 fn from_pyarrow_bound(ob: &Bound<PyAny>) -> PyResult<Self> {
643 let reader: Box<dyn RecordBatchReader> =
644 Box::new(RecordBatchStreamReader::from_pyarrow_bound(ob)?);
645 Self::try_from(reader).map_err(|err| PyValueError::new_err(err.to_string()))
646 }
647}
648
649impl IntoPyArrow for Table {
651 type_hint!(OUTPUT_TYPE = type_hint_identifier!("pyarrow", "Table"));
652
653 fn into_pyarrow(self, py: Python) -> PyResult<Bound<PyAny>> {
654 let py_batches = PyList::new(py, self.record_batches.into_iter().map(PyArrowType))?;
655 let py_schema = PyArrowType(Arc::unwrap_or_clone(self.schema));
656
657 let kwargs = PyDict::new(py);
658 kwargs.set_item("schema", py_schema)?;
659
660 table_class(py)?.call_method("from_batches", (py_batches,), Some(&kwargs))
661 }
662}
663
664fn array_class(py: Python<'_>) -> PyResult<&Bound<'_, PyType>> {
665 static TYPE: PyOnceLock<Py<PyType>> = PyOnceLock::new();
666 TYPE.import(py, "pyarrow", "Array")
667}
668
669fn record_batch_class(py: Python<'_>) -> PyResult<&Bound<'_, PyType>> {
670 static TYPE: PyOnceLock<Py<PyType>> = PyOnceLock::new();
671 TYPE.import(py, "pyarrow", "RecordBatch")
672}
673
674fn record_batch_reader_class(py: Python<'_>) -> PyResult<&Bound<'_, PyType>> {
675 static TYPE: PyOnceLock<Py<PyType>> = PyOnceLock::new();
676 TYPE.import(py, "pyarrow", "RecordBatchReader")
677}
678
679fn data_type_class(py: Python<'_>) -> PyResult<&Bound<'_, PyType>> {
680 static TYPE: PyOnceLock<Py<PyType>> = PyOnceLock::new();
681 TYPE.import(py, "pyarrow", "DataType")
682}
683
684fn field_class(py: Python<'_>) -> PyResult<&Bound<'_, PyType>> {
685 static TYPE: PyOnceLock<Py<PyType>> = PyOnceLock::new();
686 TYPE.import(py, "pyarrow", "Field")
687}
688
689fn schema_class(py: Python<'_>) -> PyResult<&Bound<'_, PyType>> {
690 static TYPE: PyOnceLock<Py<PyType>> = PyOnceLock::new();
691 TYPE.import(py, "pyarrow", "Schema")
692}
693
694fn table_class(py: Python<'_>) -> PyResult<&Bound<'_, PyType>> {
695 static TYPE: PyOnceLock<Py<PyType>> = PyOnceLock::new();
696 TYPE.import(py, "pyarrow", "Table")
697}
698
699#[derive(Debug)]
705pub struct PyArrowType<T>(pub T);
706
707impl<T: FromPyArrow> FromPyObject<'_, '_> for PyArrowType<T> {
708 type Error = PyErr;
709
710 type_hint!(INPUT_TYPE = <T as FromPyArrow>::INPUT_TYPE);
711
712 fn extract(value: Borrowed<'_, '_, PyAny>) -> PyResult<Self> {
713 Ok(Self(T::from_pyarrow_bound(&value)?))
714 }
715}
716
717impl<'py, T: IntoPyArrow> IntoPyObject<'py> for PyArrowType<T> {
718 type Target = PyAny;
719
720 type Output = Bound<'py, Self::Target>;
721
722 type Error = PyErr;
723
724 type_hint!(OUTPUT_TYPE = <T as IntoPyArrow>::OUTPUT_TYPE);
725
726 fn into_pyobject(self, py: Python<'py>) -> PyResult<Self::Output> {
727 self.0.into_pyarrow(py)
728 }
729}
730
731impl<T> From<T> for PyArrowType<T> {
732 fn from(s: T) -> Self {
733 Self(s)
734 }
735}
736
737fn call_capsule_method_if_exists<'py>(
738 object: &Bound<'py, PyAny>,
739 method_name: &Bound<'py, PyString>,
740) -> PyResult<Option<Bound<'py, PyCapsule>>> {
741 let Some(method) = object.getattr_opt(method_name)? else {
742 return Ok(None);
743 };
744 Ok(Some(method.call0()?.extract().map_err(
745 |e: CastError| {
746 wrapping_type_error(
747 object.py(),
748 e.into(),
749 format!("Expected {method_name} to return a capsule."),
750 )
751 },
752 )?))
753}
754
755fn call_arrow_c_array_method_if_exists<'py>(
756 object: &Bound<'py, PyAny>,
757) -> PyResult<Option<(Bound<'py, PyCapsule>, Bound<'py, PyCapsule>)>> {
758 let Some(method) = object.getattr_opt(intern!(object.py(), "__arrow_c_array__"))? else {
759 return Ok(None);
760 };
761 Ok(Some(method.call0()?.extract().map_err(|e| {
762 wrapping_type_error(
763 object.py(),
764 e,
765 "Expected __arrow_c_array__ to return a tuple of (schema, array) capsules.".into(),
766 )
767 })?))
768}
769
770fn extract_capsule<T>(
771 capsule: &Bound<PyCapsule>,
772 capsule_name: &CStr,
773 method_name: &'static str,
774) -> PyResult<NonNull<T>> {
775 Ok(capsule
776 .pointer_checked(Some(capsule_name))
777 .map_err(|e| {
778 wrapping_type_error(
779 capsule.py(),
780 e,
781 format!(
782 "Expected {method_name} to return a {} capsule.",
783 capsule_name.to_str().unwrap(),
784 ),
785 )
786 })?
787 .cast::<T>())
788}
789
790fn wrapping_type_error(py: Python<'_>, error: PyErr, message: String) -> PyErr {
791 let e = PyTypeError::new_err(message);
792 e.set_cause(py, Some(error));
793 e
794}
795
796#[cfg(all(test, feature = "experimental-inspect"))]
797mod introspection_tests {
798 use super::*;
799 use pyo3::{FromPyObject, IntoPyObject};
800
801 fn input_type<T: FromPyArrow>() -> String {
803 <PyArrowType<T> as FromPyObject<'_, '_>>::INPUT_TYPE.to_string()
804 }
805
806 fn output_type<T: IntoPyArrow>() -> String
808 where
809 PyArrowType<T>: for<'py> IntoPyObject<'py>,
810 {
811 <PyArrowType<T> as IntoPyObject<'_>>::OUTPUT_TYPE.to_string()
812 }
813
814 #[test]
815 fn scalar_types_map_to_their_pyarrow_class() {
816 assert_eq!(input_type::<DataType>(), "pyarrow.DataType");
817 assert_eq!(output_type::<DataType>(), "pyarrow.DataType");
818 assert_eq!(input_type::<Field>(), "pyarrow.Field");
819 assert_eq!(output_type::<Field>(), "pyarrow.Field");
820 assert_eq!(input_type::<Schema>(), "pyarrow.Schema");
821 assert_eq!(output_type::<Schema>(), "pyarrow.Schema");
822 assert_eq!(input_type::<RecordBatch>(), "pyarrow.RecordBatch");
823 assert_eq!(output_type::<RecordBatch>(), "pyarrow.RecordBatch");
824 }
825
826 #[test]
828 fn array_data_maps_to_pyarrow_array() {
829 assert_eq!(input_type::<ArrayData>(), "pyarrow.Array");
830 assert_eq!(output_type::<ArrayData>(), "pyarrow.Array");
831 }
832
833 #[test]
836 fn vec_is_iterable_in_and_list_out() {
837 assert_eq!(
838 input_type::<Vec<RecordBatch>>(),
839 "collections.abc.Iterable[pyarrow.RecordBatch]"
840 );
841 assert_eq!(
842 output_type::<Vec<RecordBatch>>(),
843 "builtins.list[pyarrow.RecordBatch]"
844 );
845 }
846
847 #[test]
850 fn readers_and_tables_map_to_their_pyarrow_class() {
851 assert_eq!(
852 input_type::<RecordBatchStreamReader>(),
853 "pyarrow.RecordBatchReader | pyarrow.Table"
854 );
855 assert_eq!(
856 output_type::<RecordBatchStreamReader>(),
857 "pyarrow.RecordBatchReader"
858 );
859 assert_eq!(
860 output_type::<Box<dyn RecordBatchReader + Send>>(),
861 "pyarrow.RecordBatchReader"
862 );
863 assert_eq!(
864 input_type::<Table>(),
865 "pyarrow.RecordBatchReader | pyarrow.Table"
866 );
867 assert_eq!(output_type::<Table>(), "pyarrow.Table");
868 }
869}