pitrou commented on code in PR #37797:
URL: https://github.com/apache/arrow/pull/37797#discussion_r1345665191


##########
python/pyarrow/ipc.pxi:
##########
@@ -815,6 +817,73 @@ cdef class RecordBatchReader(_Weakrefable):
         self.reader = c_reader
         return self
 
+    def __arrow_c_stream__(self, requested_schema=None):
+        """
+        Export to a C ArrowArrayStream PyCapsule.
+
+        Parameters
+        ----------
+        requested_schema: Schema, default None
+            The schema to which the stream should be casted. Currently, this is
+            not supported and will raise a NotImplementedError if the schema 
+            doesn't match the current schema.
+
+        Returns
+        -------
+        PyCapsule
+            A capsule containing a C ArrowArrayStream struct.
+        """
+        cdef:
+            ArrowArrayStream* c_stream = 
<ArrowArrayStream*>malloc(sizeof(ArrowArrayStream))
+
+        if requested_schema is not None:
+            out_schema = Schema._import_from_c_capsule(requested_schema)
+            # TODO: figure out a way to check if one schema is castable to
+            # another. Once we have that, we can perform validation here and
+            # if successful creating a wrapping reader that casts each batch.
+            if self.schema != out_schema:
+                raise NotImplementedError("Casting to requested_schema")
+
+        with nogil:
+            check_status(ExportRecordBatchReader(self.reader, c_stream))
+
+        return PyCapsule_New(c_stream, "arrow_array_stream", 
&pycapsule_stream_deleter)
+
+    @staticmethod
+    def _import_from_c_capsule(stream):
+        """
+        Import RecordBatchReader from a C ArrowArrayStream PyCapsule.
+
+        Parameters
+        ----------
+        stream: PyCapsule
+            A capsule containing a C ArrowArrayStream PyCapsule.
+
+        Returns
+        -------
+        RecordBatchReader
+        """
+        cdef:
+            ArrowArrayStream* c_stream
+            shared_ptr[CRecordBatchReader] c_reader
+            RecordBatchReader self
+
+        # sanity checks
+        if not PyCapsule_IsValid(stream, 'arrow_array_stream'):
+            raise ValueError(

Review Comment:
   You can also let PyCapsule_GetPointer raise its own exception.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to