rok commented on code in PR #55811:
URL: https://github.com/apache/arrow/pull/55811#discussion_r4768699488
##########
python/pyarrow/array.pxi:
##########
@@ -2717,6 +2717,68 @@ cdef class DurationArray(NumericArray):
"""
+cdef class MonthIntervalArray(Array):
+ """
+ Concrete class for Arrow arrays of interval[month] data type.
+ """
+
+ def to_pylist(self, *, maps_as_pydicts=None):
+ """
+ Convert to a list of native Python objects.
+
+ pyarrow.Month is used as the native representation.
+
+ Parameters
+ ----------
+ maps_as_pydicts : str, optional, default `None`
+ Valid values are `None`, 'lossy', or 'strict'.
+ This parameter is ignored for non-nested Scalars.
+
+ Returns
+ -------
+ lst : list
+ """
+ cdef:
+ CResult[PyObject*] maybe_py_list
+ PyObject* py_list
+ CMonthIntervalArray* array
+ array = <CMonthIntervalArray*>self.sp_array.get()
Review Comment:
:robot: Ensure device-backed (e.g. CUDA) arrays raise `NotImplementedError`
rather than reading non-CPU buffers on the host, matching `Array.to_pylist()`.
(Pre-existing `MonthDayNanoIntervalArray.to_pylist()` has the same gap if you
want to guard all three.)
```suggestion
self._assert_cpu()
array = <CMonthIntervalArray*>self.sp_array.get()
```
##########
python/pyarrow/src/arrow/python/datetime.cc:
##########
@@ -642,6 +696,47 @@ struct PyListAssigner {
} // namespace
+Result<PyObject*> MonthIntervalArrayToPyList(const MonthIntervalArray& array) {
+ OwnedRef out_list(PyList_New(array.length()));
+ RETURN_IF_PYERROR();
+ PyListAssigner out_objects(out_list.obj());
+ auto& interval_array = arrow::internal::checked_cast<const
MonthIntervalArray&>(array);
+ RETURN_NOT_OK(internal::WriteArrayObjects(
+ interval_array,
Review Comment:
:robot: `array` is already `const MonthIntervalArray&`, so the
`checked_cast` is redundant (same in `DayTimeIntervalArrayToPyList` below).
```suggestion
RETURN_NOT_OK(internal::WriteArrayObjects(
array,
```
##########
python/pyarrow/types.py:
##########
@@ -38,7 +38,8 @@
lib.Type_DECIMAL256}
_DATE_TYPES = {lib.Type_DATE32, lib.Type_DATE64}
_TIME_TYPES = {lib.Type_TIME32, lib.Type_TIME64}
-_INTERVAL_TYPES = {lib.Type_INTERVAL_MONTH_DAY_NANO}
+_INTERVAL_TYPES = {lib.Type_INTERVAL_MONTHS, lib.Type_INTERVAL_DAY_TIME,
+ lib.Type_INTERVAL_MONTH_DAY_NANO}
Review Comment:
:robot: Now that `INTERVAL_MONTHS` and `INTERVAL_DAY_TIME` are supported,
let's also remove/update the stale note in `TypesEnum`'s docstring right below
(lines 52–53).
##########
python/pyarrow/array.pxi:
##########
@@ -2717,6 +2717,68 @@ cdef class DurationArray(NumericArray):
"""
+cdef class MonthIntervalArray(Array):
+ """
+ Concrete class for Arrow arrays of interval[month] data type.
+ """
+
+ def to_pylist(self, *, maps_as_pydicts=None):
+ """
+ Convert to a list of native Python objects.
+
+ pyarrow.Month is used as the native representation.
+
+ Parameters
+ ----------
+ maps_as_pydicts : str, optional, default `None`
+ Valid values are `None`, 'lossy', or 'strict'.
+ This parameter is ignored for non-nested Scalars.
+
+ Returns
+ -------
+ lst : list
+ """
+ cdef:
+ CResult[PyObject*] maybe_py_list
+ PyObject* py_list
+ CMonthIntervalArray* array
+ array = <CMonthIntervalArray*>self.sp_array.get()
+ maybe_py_list = MonthIntervalArrayToPyList(deref(array))
+ py_list = GetResultValue(maybe_py_list)
+ return PyObject_to_object(py_list)
+
+
+cdef class DayTimeIntervalArray(Array):
+ """
+ Concrete class for Arrow arrays of interval[day_time] data type.
+ """
+
+ def to_pylist(self, *, maps_as_pydicts=None):
+ """
+ Convert to a list of native Python objects.
+
+ pyarrow.DayTime is used as the native representation.
+
+ Parameters
+ ----------
+ maps_as_pydicts : str, optional, default `None`
+ Valid values are `None`, 'lossy', or 'strict'.
+ This parameter is ignored for non-nested Scalars.
+
+ Returns
+ -------
+ lst : list
+ """
+ cdef:
+ CResult[PyObject*] maybe_py_list
+ PyObject* py_list
+ CDayTimeIntervalArray* array
+ array = <CDayTimeIntervalArray*>self.sp_array.get()
Review Comment:
:robot: Same CPU guard as `MonthIntervalArray.to_pylist()` so non-CPU
buffers aren't read on the host.
```suggestion
self._assert_cpu()
array = <CDayTimeIntervalArray*>self.sp_array.get()
```
##########
python/pyarrow/tests/test_compute.py:
##########
@@ -4631,3 +4631,32 @@ def test_winsorize():
result = pc.winsorize(
arr, options=pc.WinsorizeOptions(lower_limit=0.1, upper_limit=0.8))
assert result.to_pylist() == [8, 4, 8, 8, 5, 3, 7, 2, 2, 6]
+
+
+def test_interval_between():
+ arr1 = pa.array(
+ [datetime.datetime(2020, 1, 1), None, datetime.datetime(1900, 12, 13)],
+ type=pa.timestamp('s')
+ )
+ arr2 = pa.array(
+ [datetime.datetime(2020, 5, 5), datetime.datetime(2020, 10, 1),
+ datetime.datetime(2020, 1, 1)],
+ type=pa.timestamp('s')
+ )
+ result = pc.month_day_nano_interval_between(arr1, arr2)
+ assert isinstance(result, pa.MonthDayNanoIntervalArray)
+ assert isinstance(result[0], pa.MonthDayNanoIntervalScalar)
+
+ result = pc.month_interval_between(arr1, arr2)
+ assert isinstance(result, pa.MonthIntervalArray)
+ assert isinstance(result[0], pa.MonthIntervalScalar)
+ assert str(result[0]) == "4M"
+ assert result.to_pylist() == [pa.Month([4]), None, pa.Month([1429])]
+
+ result = pc.day_time_interval_between(arr1, arr2)
+ assert isinstance(result, pa.DayTimeIntervalArray)
+ assert isinstance(result[0], pa.DayTimeIntervalScalar)
+ assert str(result[0]) == "125d0ms"
+ assert result.to_pylist() == [pa.DayTime([125, 0]),
+ None,
+ pa.DayTime([43483, 0])]
Review Comment:
:robot: Consider also covering negative intervals (e.g. `arr2, arr1`) and
sliced/empty arrays (`result[1:].to_pylist()`, `result[:0].to_pylist()`) to
verify signed `int32_t` handling and non-zero offsets / empty lengths in
`to_pylist()`.
##########
python/pyarrow-stubs/__init__.pyi:
##########
@@ -128,6 +128,12 @@ from pyarrow.lib import (
MapType as MapType,
MemoryManager as MemoryManager,
MemoryPool as MemoryPool,
+ Month as Month,
+ MonthIntervalArray as MonthIntervalArray,
+ MonthIntervalScalar as MonthIntervalScalar,
+ DayTime as DayTime,
+ DayTimeIntervalArray as DayTimeIntervalArray,
+ DayTimeIntervalScalar as DayTimeIntervalScalar,
Review Comment:
:robot: To keep the stub import blocks alphabetically sorted, `DayTime`,
`DayTimeIntervalArray`, `DayTimeIntervalScalar` (and `day_time_interval` below)
can go under `D`/`d`. Same for `DayTime` in
`python/pyarrow-stubs/__lib/scalar.pyi` and `DayTimeIntervalType` in
`python/pyarrow-stubs/__lib/types.pyi` and `python/pyarrow-stubs/types.pyi`.
##########
docs/source/python/api/arrays.rst:
##########
@@ -148,6 +150,8 @@ classes may expose data type-specific methods or properties.
Date64Scalar
TimestampScalar
DurationScalar
+ MonthIntervalScalar
+ DayTimeIntervalScalar
MonthDayNanoIntervalScalar
Review Comment:
:robot: Both `to_pylist()` and `as_py()` reference `pyarrow.Month` and
`pyarrow.DayTime` as the returned Python types, but neither (nor
`MonthDayNano`) is listed in the API reference `.rst` files yet, so Sphinx
doesn't generate reference pages for their fields/constructors. Consider adding
a small `autosummary` entry for `Month`, `DayTime`, and `MonthDayNano` (e.g.,
at the bottom of `arrays.rst` or in `datatypes.rst`), and noting `or None` in
the `Returns` docstrings of `MonthIntervalScalar.as_py()` /
`DayTimeIntervalScalar.as_py()`. (No narrative `data.rst` additions needed
until Python-to-Arrow creation lands in the follow-up.)
##########
python/pyarrow/includes/libarrow.pxd:
##########
@@ -1377,6 +1385,18 @@ cdef extern from "arrow/api.h" namespace "arrow" nogil:
cdef cppclass CDurationScalar" arrow::DurationScalar"(CScalar):
int64_t value
+ cdef cppclass CMonthIntervalScalar \
+ "arrow::MonthIntervalScalar"(CScalar):
+ int32_t value
+
+ cdef cppclass CDayMilliseconds"
arrow::DayTimeIntervalType::DayMilliseconds":
+ int32_t days
+ int32_t milliseconds
+
+ cdef cppclass CDayTimeIntervalScalar \
+ "arrow::DayTimeIntervalScalar"(CScalar):
+ CDayMilliseconds value
Review Comment:
:robot: Since scalar conversion now lives in C++ (`datetime.cc`), these
`.value` fields and `CDayMilliseconds` aren't referenced from Cython —
simplifying to `pass` matches `CMonthDayNanoIntervalScalar` below unless the
follow-up will read them directly from Cython.
```suggestion
cdef cppclass CMonthIntervalScalar \
"arrow::MonthIntervalScalar"(CScalar):
pass
cdef cppclass CDayTimeIntervalScalar \
"arrow::DayTimeIntervalScalar"(CScalar):
pass
```
##########
python/pyarrow/scalar.pxi:
##########
@@ -904,6 +904,92 @@ cdef class DurationScalar(Scalar):
return datetime.timedelta(microseconds=sp.value // 1000)
+cdef class MonthIntervalScalar(Scalar):
+ """
+ Concrete class for month interval scalars.
+ """
+
+ @property
+ def value(self):
+ """
+ Same as self.as_py()
+ """
+ return self.as_py()
+
+ def __repr__(self):
+ return '<pyarrow.{}: {}>'.format(
+ self.__class__.__name__, frombytes(self.wrapped.get().ToString())
+ )
+
+ def __str__(self):
+ return frombytes(self.wrapped.get().ToString())
+
+ def as_py(self, *, maps_as_pydicts=None):
Review Comment:
:robot: Now that `as_py()` returns `pa.Month`, do we still want these
`__repr__`/`__str__` overrides? Inheriting `Scalar.__repr__`/`__str__` (as
`MonthDayNanoIntervalScalar` does) keeps all three interval scalars consistent
and avoids formatting null scalars as `null` instead of `None`
(`Scalar::ToString()` returns `"null"` for invalid scalars).
Same for `DayTimeIntervalScalar` below (and the corresponding `str(...)`
assertions in `test_compute.py` / doctests in `types.pxi`).
```suggestion
def as_py(self, *, maps_as_pydicts=None):
```
--
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]