You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2021/09/13 23:13:09 UTC

[GitHub] [arrow] edponce opened a new pull request #11147: ARROW-13327: [Python] Improve consistency of explicit C++ types in PyArrow files

edponce opened a new pull request #11147:
URL: https://github.com/apache/arrow/pull/11147


   This PR updates PyArrow compute bindings for FunctionOptions and makes their implementation consistent.


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] edponce commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
edponce commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r713239278



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -327,23 +317,17 @@ cdef class Function(_Weakrefable):
             CExecContext c_exec_ctx = CExecContext(pool)
             vector[CDatum] c_args
             CDatum result
-
         _pack_compute_args(args, &c_args)
-
         if options is not None:
             c_options = options.get_options()
-

Review comment:
       I agree, I personally prefer whitespace when new context follows, but I have noticed that a lot of Arrow code is clumped together. I reverted this change.




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] jorisvandenbossche commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
jorisvandenbossche commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r713623308



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -1052,37 +1055,31 @@ cdef class _DayOfWeekOptions(FunctionOptions):
 
 
 class DayOfWeekOptions(_DayOfWeekOptions):
-    def __init__(self, one_based_numbering=False, week_start=1):
+    def __init__(self, *, one_based_numbering=False, week_start=1):
         self._set_options(one_based_numbering, week_start)
 
 
 cdef class _AssumeTimezoneOptions(FunctionOptions):
+    _ambiguous_map = {
+        "raise": CAssumeTimezoneAmbiguous_AMBIGUOUS_RAISE,
+        "earliest": CAssumeTimezoneAmbiguous_AMBIGUOUS_EARLIEST,
+        "latest": CAssumeTimezoneAmbiguous_AMBIGUOUS_LATEST,
+    }
+    _nonexistent_map = {
+        "raise": CAssumeTimezoneNonexistent_NONEXISTENT_RAISE,
+        "earliest": CAssumeTimezoneNonexistent_NONEXISTENT_EARLIEST,
+        "latest": CAssumeTimezoneNonexistent_NONEXISTENT_LATEST,
+    }
+
     def _set_options(self, timezone, ambiguous, nonexistent):
-        ambiguous_dict = {
-            'raise': CAssumeTimezoneAmbiguous_AMBIGUOUS_RAISE,
-            'earliest': CAssumeTimezoneAmbiguous_AMBIGUOUS_EARLIEST,
-            'latest': CAssumeTimezoneAmbiguous_AMBIGUOUS_LATEST,
-        }
-        nonexistent_dict = {
-            'raise': CAssumeTimezoneNonexistent_NONEXISTENT_RAISE,
-            'earliest': CAssumeTimezoneNonexistent_NONEXISTENT_EARLIEST,
-            'latest': CAssumeTimezoneNonexistent_NONEXISTENT_LATEST,
-        }
-
-        if ambiguous not in ambiguous_dict:
-            raise ValueError(
-                "{!r} is not a valid 'ambiguous' keyword".format(ambiguous)
-            )
-        if nonexistent not in nonexistent_dict:
-            raise ValueError(
-                "{!r} is not a valid 'nonexistent' keyword".format(
-                    nonexistent)
-            )
+        if ambiguous not in self._ambiguous_map:
+            _raise_invalid_function_option(ambiguous, "ambiguous")
+        if nonexistent not in self._nonexistent_map:
+            _raise_invalid_function_option(nonexistent, "nonexistent")

Review comment:
       ```suggestion
               _raise_invalid_function_option(ambiguous, "'ambiguous' value")
           if nonexistent not in self._nonexistent_map:
               _raise_invalid_function_option(nonexistent, "'nonexistent' value")
   ```
   
   In this case there needs to be an extra word I think (otherwise you get " ... is not a valid ambiguous" as error message)




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] pitrou commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
pitrou commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r712117470



##########
File path: python/pyarrow/tests/test_compute.py
##########
@@ -1921,9 +1937,9 @@ def validate_select_k(select_k_indices, tbl, sort_keys, stable_sort=False):
 
     with pytest.raises(ValueError, match="select_k_unstable requires "
                        "a non-empty `sort_keys`"):
-        pc.select_k_unstable(table, k=2)
+        pc.select_k_unstable(table, k=2, sort_keys=[])
 
-    with pytest.raises(ValueError, match="not a valid order"):
+    with pytest.raises(ValueError, match="not a valid 'sort order'"):

Review comment:
       Nit, but the quotes around "sort order" look a bit gratuitous?




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] jorisvandenbossche commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
jorisvandenbossche commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r707962252



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -899,26 +900,26 @@ cdef class _TakeOptions(FunctionOptions):
 
 
 class TakeOptions(_TakeOptions):
-    def __init__(self, *, boundscheck=True):
+    def __init__(self, boundscheck=True):

Review comment:
       I would keep this (it's to force `boundscheck` to be a keyword argument, and never positional argument)
   
   (and the same for some cases below)

##########
File path: python/pyarrow/_compute.pyx
##########
@@ -690,99 +700,91 @@ class CastOptions(_CastOptions):
 
 
 cdef class _ElementWiseAggregateOptions(FunctionOptions):
-    def _set_options(self, bint skip_nulls):
+    def _set_options(self, skip_nulls):
         self.wrapped.reset(new CElementWiseAggregateOptions(skip_nulls))
 
 
 class ElementWiseAggregateOptions(_ElementWiseAggregateOptions):
-    def __init__(self, bint skip_nulls=True):
+    def __init__(self, skip_nulls=True):
         self._set_options(skip_nulls)
 
 
 cdef CRoundMode unwrap_round_mode(round_mode) except *:
-    if round_mode == 'down':
-        return CRoundMode_DOWN
-    elif round_mode == 'up':
-        return CRoundMode_UP
-    elif round_mode == 'towards_zero':
-        return CRoundMode_TOWARDS_ZERO
-    elif round_mode == 'towards_infinity':
-        return CRoundMode_TOWARDS_INFINITY
-    elif round_mode == 'half_down':
-        return CRoundMode_HALF_DOWN
-    elif round_mode == 'half_up':
-        return CRoundMode_HALF_UP
-    elif round_mode == 'half_towards_zero':
-        return CRoundMode_HALF_TOWARDS_ZERO
-    elif round_mode == 'half_towards_infinity':
-        return CRoundMode_HALF_TOWARDS_INFINITY
-    elif round_mode == 'half_to_even':
-        return CRoundMode_HALF_TO_EVEN
-    elif round_mode == 'half_to_odd':
-        return CRoundMode_HALF_TO_ODD
-    else:
-        raise ValueError('"{}" is not a valid round mode'.format(round_mode))
+    round_mode_dict = {
+        "down": CRoundMode_DOWN,
+        "up": CRoundMode_UP,
+        "towards_zero": CRoundMode_TOWARDS_ZERO,
+        "towards_infinity": CRoundMode_TOWARDS_INFINITY,
+        "half_down": CRoundMode_HALF_DOWN,
+        "half_up": CRoundMode_HALF_UP,
+        "half_towards_zero": CRoundMode_HALF_TOWARDS_ZERO,
+        "half_towards_infinity": CRoundMode_HALF_TOWARDS_INFINITY,
+        "half_to_even": CRoundMode_HALF_TO_EVEN,
+        "half_to_odd": CRoundMode_HALF_TO_ODD,
+    }
+
+    if round_mode not in round_mode_dict:
+        raise ValueError(f'"{round_mode}" is not a valid round mode')
 

Review comment:
       Is there missing a return value here?

##########
File path: python/pyarrow/_compute.pyx
##########
@@ -844,53 +846,52 @@ class ExtractRegexOptions(_ExtractRegexOptions):
 
 
 cdef class _SliceOptions(FunctionOptions):
-    def _set_options(self, int64_t start, int64_t stop, int64_t step):
+    def _set_options(self, start, stop, step):

Review comment:
       Is there a reason to remove them both here and in the init just below?

##########
File path: python/pyarrow/_compute.pyx
##########
@@ -844,53 +846,52 @@ class ExtractRegexOptions(_ExtractRegexOptions):
 
 
 cdef class _SliceOptions(FunctionOptions):
-    def _set_options(self, int64_t start, int64_t stop, int64_t step):
+    def _set_options(self, start, stop, step):
         self.wrapped.reset(new CSliceOptions(start, stop, step))
 
 
 class SliceOptions(_SliceOptions):
-    def __init__(self, int64_t start, int64_t stop=sys.maxsize,
-                 int64_t step=1):
+    def __init__(self, start, stop=sys.maxsize, step=1):
         self._set_options(start, stop, step)
 
 
 cdef class _FilterOptions(FunctionOptions):
-    def _set_options(self, null_selection_behavior):
-        if null_selection_behavior == 'drop':
-            self.wrapped.reset(
-                new CFilterOptions(CFilterNullSelectionBehavior_DROP))
-        elif null_selection_behavior == 'emit_null':
-            self.wrapped.reset(
-                new CFilterOptions(CFilterNullSelectionBehavior_EMIT_NULL))
-        else:
+    null_selection_dict = {
+        "drop": CFilterNullSelectionBehavior_DROP,
+        "emit_null": CFilterNullSelectionBehavior_EMIT_NULL,
+    }
+
+    def _set_options(self, null_selection):
+        if null_selection not in null_selection_dict:
             raise ValueError(
-                '"{}" is not a valid null_selection_behavior'
-                .format(null_selection_behavior))
+                f'"{null_selection}" is not a valid null_selection_behavior')
+        self.wrapped.reset(
+            new CFilterOptions(null_selection_dict[null_selection])
+        )
 
 
 class FilterOptions(_FilterOptions):
-    def __init__(self, null_selection_behavior='drop'):
-        self._set_options(null_selection_behavior)
+    def __init__(self, null_selection="drop"):

Review comment:
       This is changing the name of the keyword in the public function?




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] pitrou commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
pitrou commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r712115997



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -690,99 +677,96 @@ class CastOptions(_CastOptions):
 
 
 cdef class _ElementWiseAggregateOptions(FunctionOptions):
-    def _set_options(self, bint skip_nulls):
+    def _set_options(self, skip_nulls):
         self.wrapped.reset(new CElementWiseAggregateOptions(skip_nulls))
 
 
 class ElementWiseAggregateOptions(_ElementWiseAggregateOptions):
-    def __init__(self, bint skip_nulls=True):
+    def __init__(self, skip_nulls=True):

Review comment:
       Should this one become keyword-only? `ElementWiseAggregateOptions(true)` isn't very explicit.




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] edponce edited a comment on pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
edponce edited a comment on pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#issuecomment-922733817


   The FunctionOptions that were modified w.r.t. to positional/keyword-only args are:
   ```python
   MatchSubstringOptions(self, pattern, *, ignore_case)
   ReplaceSubstringOptions(self, pattern, replacement, *, max_replacements)
   ScalarAggregateOptions(self, *, skip_nulls, min_count)
   ModeOptions(self, n, *, skip_nulls, min_count)
   SetLookupOptions(self, value_set, *, skip_nulls)
   DayOfWeekOptions(self, *, one_based_numbering, week_start)
   NullOptions(self, *, nan_is_null)
   SplitPatternOptions(self, pattern, *, max_splits, reverse)
   ArraySortOptions(self, order)
   ElementWiseAggregateOptions(self, *, skip_nulls)
   ```


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] edponce commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
edponce commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r708416214



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -844,53 +846,52 @@ class ExtractRegexOptions(_ExtractRegexOptions):
 
 
 cdef class _SliceOptions(FunctionOptions):
-    def _set_options(self, int64_t start, int64_t stop, int64_t step):
+    def _set_options(self, start, stop, step):

Review comment:
       Yes, they were removed deliberately. The option values are passed to the constructors of the corresponding FunctionOptions which are defined in [includes/libarrow.pxd](https://github.com/apache/arrow/blob/master/python/pyarrow/includes/libarrow.pxd) and expose the explicit C types. Invalid types from public functions in .pyx get "validated" during initialization in constructors. If the types are included in the `cdef _XXXOptions`, then inputs would be "validated" here, basically one line of code earlier. Duplicating types in the `_FunctionOptions` methods in `_compute.pyx` does not adds any different functionality, but requires developers/maintainers to ensure consistency between these files and the C++ option definitions. I think removing them from .pyx file is a better approach.




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] jorisvandenbossche commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
jorisvandenbossche commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r709241402



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -844,53 +846,52 @@ class ExtractRegexOptions(_ExtractRegexOptions):
 
 
 cdef class _SliceOptions(FunctionOptions):
-    def _set_options(self, int64_t start, int64_t stop, int64_t step):
+    def _set_options(self, start, stop, step):

Review comment:
       OK, I see, thanks for the explanation.




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] edponce commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
edponce commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r713626665



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -1052,37 +1055,31 @@ cdef class _DayOfWeekOptions(FunctionOptions):
 
 
 class DayOfWeekOptions(_DayOfWeekOptions):
-    def __init__(self, one_based_numbering=False, week_start=1):
+    def __init__(self, *, one_based_numbering=False, week_start=1):
         self._set_options(one_based_numbering, week_start)
 
 
 cdef class _AssumeTimezoneOptions(FunctionOptions):
+    _ambiguous_map = {
+        "raise": CAssumeTimezoneAmbiguous_AMBIGUOUS_RAISE,
+        "earliest": CAssumeTimezoneAmbiguous_AMBIGUOUS_EARLIEST,
+        "latest": CAssumeTimezoneAmbiguous_AMBIGUOUS_LATEST,
+    }
+    _nonexistent_map = {
+        "raise": CAssumeTimezoneNonexistent_NONEXISTENT_RAISE,
+        "earliest": CAssumeTimezoneNonexistent_NONEXISTENT_EARLIEST,
+        "latest": CAssumeTimezoneNonexistent_NONEXISTENT_LATEST,
+    }
+
     def _set_options(self, timezone, ambiguous, nonexistent):
-        ambiguous_dict = {
-            'raise': CAssumeTimezoneAmbiguous_AMBIGUOUS_RAISE,
-            'earliest': CAssumeTimezoneAmbiguous_AMBIGUOUS_EARLIEST,
-            'latest': CAssumeTimezoneAmbiguous_AMBIGUOUS_LATEST,
-        }
-        nonexistent_dict = {
-            'raise': CAssumeTimezoneNonexistent_NONEXISTENT_RAISE,
-            'earliest': CAssumeTimezoneNonexistent_NONEXISTENT_EARLIEST,
-            'latest': CAssumeTimezoneNonexistent_NONEXISTENT_LATEST,
-        }
-
-        if ambiguous not in ambiguous_dict:
-            raise ValueError(
-                "{!r} is not a valid 'ambiguous' keyword".format(ambiguous)
-            )
-        if nonexistent not in nonexistent_dict:
-            raise ValueError(
-                "{!r} is not a valid 'nonexistent' keyword".format(
-                    nonexistent)
-            )
+        if ambiguous not in self._ambiguous_map:
+            _raise_invalid_function_option(ambiguous, "ambiguous")
+        if nonexistent not in self._nonexistent_map:
+            _raise_invalid_function_option(nonexistent, "nonexistent")

Review comment:
       What about "'ambiguous' timezone assumption"?




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] edponce commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
edponce commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r712428399



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -569,6 +543,10 @@ cdef class FunctionOptions(_Weakrefable):
         return self.get_options().Equals(deref(other.get_options()))
 
 
+def raise_invalid_function_option(value, description, *, error="keyword"):

Review comment:
       Do you think we should include it as a private method of `FunctionOptions` or leave it as a free standing function? 




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] jorisvandenbossche commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
jorisvandenbossche commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r713628345



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -1052,37 +1055,31 @@ cdef class _DayOfWeekOptions(FunctionOptions):
 
 
 class DayOfWeekOptions(_DayOfWeekOptions):
-    def __init__(self, one_based_numbering=False, week_start=1):
+    def __init__(self, *, one_based_numbering=False, week_start=1):
         self._set_options(one_based_numbering, week_start)
 
 
 cdef class _AssumeTimezoneOptions(FunctionOptions):
+    _ambiguous_map = {
+        "raise": CAssumeTimezoneAmbiguous_AMBIGUOUS_RAISE,
+        "earliest": CAssumeTimezoneAmbiguous_AMBIGUOUS_EARLIEST,
+        "latest": CAssumeTimezoneAmbiguous_AMBIGUOUS_LATEST,
+    }
+    _nonexistent_map = {
+        "raise": CAssumeTimezoneNonexistent_NONEXISTENT_RAISE,
+        "earliest": CAssumeTimezoneNonexistent_NONEXISTENT_EARLIEST,
+        "latest": CAssumeTimezoneNonexistent_NONEXISTENT_LATEST,
+    }
+
     def _set_options(self, timezone, ambiguous, nonexistent):
-        ambiguous_dict = {
-            'raise': CAssumeTimezoneAmbiguous_AMBIGUOUS_RAISE,
-            'earliest': CAssumeTimezoneAmbiguous_AMBIGUOUS_EARLIEST,
-            'latest': CAssumeTimezoneAmbiguous_AMBIGUOUS_LATEST,
-        }
-        nonexistent_dict = {
-            'raise': CAssumeTimezoneNonexistent_NONEXISTENT_RAISE,
-            'earliest': CAssumeTimezoneNonexistent_NONEXISTENT_EARLIEST,
-            'latest': CAssumeTimezoneNonexistent_NONEXISTENT_LATEST,
-        }
-
-        if ambiguous not in ambiguous_dict:
-            raise ValueError(
-                "{!r} is not a valid 'ambiguous' keyword".format(ambiguous)
-            )
-        if nonexistent not in nonexistent_dict:
-            raise ValueError(
-                "{!r} is not a valid 'nonexistent' keyword".format(
-                    nonexistent)
-            )
+        if ambiguous not in self._ambiguous_map:
+            _raise_invalid_function_option(ambiguous, "ambiguous")
+        if nonexistent not in self._nonexistent_map:
+            _raise_invalid_function_option(nonexistent, "nonexistent")

Review comment:
       The "ambiguous" is not the about the timezone, but the timestamp. So something like `'ambiguous' timestamp handling` would be OK as well I think




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] edponce commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
edponce commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r708417579



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -844,53 +846,52 @@ class ExtractRegexOptions(_ExtractRegexOptions):
 
 
 cdef class _SliceOptions(FunctionOptions):
-    def _set_options(self, int64_t start, int64_t stop, int64_t step):
+    def _set_options(self, start, stop, step):
         self.wrapped.reset(new CSliceOptions(start, stop, step))
 
 
 class SliceOptions(_SliceOptions):
-    def __init__(self, int64_t start, int64_t stop=sys.maxsize,
-                 int64_t step=1):
+    def __init__(self, start, stop=sys.maxsize, step=1):
         self._set_options(start, stop, step)
 
 
 cdef class _FilterOptions(FunctionOptions):
-    def _set_options(self, null_selection_behavior):
-        if null_selection_behavior == 'drop':
-            self.wrapped.reset(
-                new CFilterOptions(CFilterNullSelectionBehavior_DROP))
-        elif null_selection_behavior == 'emit_null':
-            self.wrapped.reset(
-                new CFilterOptions(CFilterNullSelectionBehavior_EMIT_NULL))
-        else:
+    null_selection_dict = {
+        "drop": CFilterNullSelectionBehavior_DROP,
+        "emit_null": CFilterNullSelectionBehavior_EMIT_NULL,
+    }
+
+    def _set_options(self, null_selection):
+        if null_selection not in null_selection_dict:
             raise ValueError(
-                '"{}" is not a valid null_selection_behavior'
-                .format(null_selection_behavior))
+                f'"{null_selection}" is not a valid null_selection_behavior')
+        self.wrapped.reset(
+            new CFilterOptions(null_selection_dict[null_selection])
+        )
 
 
 class FilterOptions(_FilterOptions):
-    def __init__(self, null_selection_behavior='drop'):
-        self._set_options(null_selection_behavior)
+    def __init__(self, null_selection="drop"):

Review comment:
       Yes, for symmetry it would have been better to not include the `_behavior` part but given that this was existing code and there might already be users expecting this API, I will revert this change to how it was before this PR.




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] pitrou commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
pitrou commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r712918630



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -690,99 +677,96 @@ class CastOptions(_CastOptions):
 
 
 cdef class _ElementWiseAggregateOptions(FunctionOptions):
-    def _set_options(self, bint skip_nulls):
+    def _set_options(self, skip_nulls):
         self.wrapped.reset(new CElementWiseAggregateOptions(skip_nulls))
 
 
 class ElementWiseAggregateOptions(_ElementWiseAggregateOptions):
-    def __init__(self, bint skip_nulls=True):
+    def __init__(self, *, skip_nulls=True):
         self._set_options(skip_nulls)
 
 
 cdef CRoundMode unwrap_round_mode(round_mode) except *:
-    if round_mode == 'down':
+    # TODO: Cython 0.29.x does not supports C++ scoped enums as dictionary
+    # values because they do not resolve to integers, so we use if-elses.
+    # Cython 3 fully supports C++ scoped enums resolving to integers, refer to
+    # https://cython.readthedocs.io/en/latest/src/userguide/wrapping_CPlusPlus.html#scoped-enumerations
+    if round_mode == "down":

Review comment:
       You can open a JIRA for this. Of course it's a pretty minor issue.




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] pitrou commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
pitrou commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r712921002



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -980,51 +973,45 @@ cdef class _ModeOptions(FunctionOptions):
 
 
 class ModeOptions(_ModeOptions):
-    def __init__(self, n=1, skip_nulls=True, min_count=0):
+    def __init__(self, n=1, *, skip_nulls=True, min_count=0):
         self._set_options(n, skip_nulls, min_count)
 
 
 cdef class _SetLookupOptions(FunctionOptions):
-    cdef:
-        unique_ptr[CDatum] valset
-
     def _set_options(self, value_set, c_bool skip_nulls):
+        cdef unique_ptr[CDatum] valset
         if isinstance(value_set, Array):
-            self.valset.reset(new CDatum((<Array> value_set).sp_array))
+            valset.reset(new CDatum((<Array> value_set).sp_array))
         elif isinstance(value_set, ChunkedArray):
-            self.valset.reset(
-                new CDatum((<ChunkedArray> value_set).sp_chunked_array)
-            )
+            valset.reset(
+                new CDatum((<ChunkedArray> value_set).sp_chunked_array))
         elif isinstance(value_set, Scalar):
-            self.valset.reset(new CDatum((<Scalar> value_set).unwrap()))
+            valset.reset(new CDatum((<Scalar> value_set).unwrap()))
         else:
-            raise ValueError('"{}" is not a valid value_set'.format(value_set))
-
-        self.wrapped.reset(
-            new CSetLookupOptions(deref(self.valset), skip_nulls))
+            _raise_invalid_function_option(value_set, "value set",
+                                           error="type")

Review comment:
       If the type is the problem, then perhaps `TypeError` should be raised, not `ValueError`?




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] edponce commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
edponce commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r712475283



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -690,99 +677,96 @@ class CastOptions(_CastOptions):
 
 
 cdef class _ElementWiseAggregateOptions(FunctionOptions):
-    def _set_options(self, bint skip_nulls):
+    def _set_options(self, skip_nulls):
         self.wrapped.reset(new CElementWiseAggregateOptions(skip_nulls))
 
 
 class ElementWiseAggregateOptions(_ElementWiseAggregateOptions):
-    def __init__(self, bint skip_nulls=True):
+    def __init__(self, *, skip_nulls=True):
         self._set_options(skip_nulls)
 
 
 cdef CRoundMode unwrap_round_mode(round_mode) except *:
-    if round_mode == 'down':
+    # TODO: Cython 0.29.x does not supports C++ scoped enums as dictionary
+    # values because they do not resolve to integers, so we use if-elses.
+    # Cython 3 fully supports C++ scoped enums resolving to integers, refer to
+    # https://cython.readthedocs.io/en/latest/src/userguide/wrapping_CPlusPlus.html#scoped-enumerations
+    if round_mode == "down":

Review comment:
       `RoundMode` and `SortOrder` are scoped enums but they are not fully supported (in terms of concise usage) until Cython 3. Arrow currently builds for Cython >= 0.29.x, so I left *TODO* comments ([here](https://github.com/apache/arrow/pull/11147/files#diff-439f91c435cc8136d40eaba8c168aaa1cec00f08b10ba92ce376e47f29f81814R690) and [here](https://github.com/apache/arrow/pull/11147/files#diff-439f91c435cc8136d40eaba8c168aaa1cec00f08b10ba92ce376e47f29f81814R1114)) to describe the intent here for working with scoped enums. Also, left *TODO* comments ([here](https://github.com/apache/arrow/pull/11147/files#diff-48e87fef366d65330100bf1703a542b8cb447575b6f8c3a3617741ce57854d4aR2090) and [here](https://github.com/apache/arrow/pull/11147/files#diff-48e87fef366d65330100bf1703a542b8cb447575b6f8c3a3617741ce57854d4aR1829)) for defining scoped enums in `includes/libarrow.pxd`.
   
   This is the first time I embed *TODO* comments in Arrow but think they are worthwhile. I can also keep track of these notes locally or should this go into a future JIRA issue? @pitrou please advise.




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] jorisvandenbossche commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
jorisvandenbossche commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r709256716



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -899,26 +900,26 @@ cdef class _TakeOptions(FunctionOptions):
 
 
 class TakeOptions(_TakeOptions):
-    def __init__(self, *, boundscheck=True):
+    def __init__(self, boundscheck=True):

Review comment:
       Using the rule of @westonpace to have keywords that are optional / have a default as keyword-only, is probably a good start. We can see if that gives any changes compared to the current situation.




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] edponce commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
edponce commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r713245188



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -904,59 +885,71 @@ class TakeOptions(_TakeOptions):
 
 
 cdef class _PartitionNthOptions(FunctionOptions):
-    def _set_options(self, int64_t pivot):
+    def _set_options(self, pivot):
         self.wrapped.reset(new CPartitionNthOptions(pivot))
 
 
 class PartitionNthOptions(_PartitionNthOptions):
-    def __init__(self, int64_t pivot):
+    def __init__(self, pivot):
         self._set_options(pivot)
 
 
 cdef class _MakeStructOptions(FunctionOptions):
-    def _set_options(self, field_names):
+    def _set_options(self, field_names, field_nullability, field_metadata):
         cdef:
             vector[c_string] c_field_names
-        for n in field_names:
-            c_field_names.push_back(tobytes(n))
-        self.wrapped.reset(new CMakeStructOptions(c_field_names))
+            vector[shared_ptr[const CKeyValueMetadata]] c_field_metadata
+        for name in field_names:
+            c_field_names.push_back(tobytes(name))
+        for metadata in field_metadata:
+            c_field_metadata.push_back(pyarrow_unwrap_metadata(metadata))
+        self.wrapped.reset(
+            new CMakeStructOptions(c_field_names,
+                                   field_nullability,
+                                   c_field_metadata))
 
 
 class MakeStructOptions(_MakeStructOptions):
-    def __init__(self, field_names):
-        self._set_options(field_names)
+    def __init__(self, field_names, field_nullability=None,

Review comment:
       `MakeStructOptions` was updated recently with additional mandatory parameters. All arguments are mandatory (see [C++ definition](https://github.com/apache/arrow/blob/master/cpp/src/arrow/compute/api_scalar.h#L300-L303)), so I think we should leave them positional here as well.




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] edponce edited a comment on pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
edponce edited a comment on pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#issuecomment-922733817


   The FunctionOptions that were modified w.r.t. to positional/keyword-only args are:
   ```python
   MatchSubstringOptions(self, pattern, *, ignore_case)
   ReplaceSubstringOptions(self, pattern, replacement, *, max_replacements)
   ScalarAggregateOptions(self, *, skip_nulls, min_count)
   ModeOptions(self, n, *, skip_nulls, min_count)
   SetLookupOptions(self, value_set, *, skip_nulls)
   DayOfWeekOptions(self, *, one_based_numbering, week_start)
   NullOptions(self, *, nan_is_null)
   SplitPatternOptions(self, pattern, *, max_splits, reverse)
   ArraySortOptions(self, order)
   ElementWiseAggregateOptions(self, *, skip_nulls)
   QuantileOptions(self, q, *, interpolation)
   TDigestOptions(self, q, *, delta, buffer_size)
   ```


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] pitrou closed pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
pitrou closed pull request #11147:
URL: https://github.com/apache/arrow/pull/11147


   


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] pitrou commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
pitrou commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r712115155



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -569,6 +543,10 @@ cdef class FunctionOptions(_Weakrefable):
         return self.get_options().Equals(deref(other.get_options()))
 
 
+def raise_invalid_function_option(value, description, *, error="keyword"):

Review comment:
       This is a private function, prefix it with an underscore?




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] edponce commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
edponce commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r708418292



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -899,26 +900,26 @@ cdef class _TakeOptions(FunctionOptions):
 
 
 class TakeOptions(_TakeOptions):
-    def __init__(self, *, boundscheck=True):
+    def __init__(self, boundscheck=True):

Review comment:
       I removed all the keyword arguments simply to get a code review like yours. How do we decide what options should be positional and which ones should be keyword-only?




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] edponce commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
edponce commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r708418292



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -899,26 +900,26 @@ cdef class _TakeOptions(FunctionOptions):
 
 
 class TakeOptions(_TakeOptions):
-    def __init__(self, *, boundscheck=True):
+    def __init__(self, boundscheck=True):

Review comment:
       I remove all the keyword arguments simply to get a code review like yours. How do we decide what options should be positional and which ones should be keyword-only?




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] github-actions[bot] commented on pull request #11147: ARROW-13327: [Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#issuecomment-918652127


   https://issues.apache.org/jira/browse/ARROW-13327


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] edponce commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
edponce commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r709283521



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -899,26 +900,26 @@ cdef class _TakeOptions(FunctionOptions):
 
 
 class TakeOptions(_TakeOptions):
-    def __init__(self, *, boundscheck=True):
+    def __init__(self, boundscheck=True):

Review comment:
       Ok, I started doing that (still WIP), but also noticed that in C++ FunctionOptions, there are inconsistencies between the number of constructors, the availability of a `Defaults()` method, and data members. I am looking into this (need to reach out to other developers) to check what changes we are allowed to make at this time.




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] edponce commented on pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
edponce commented on pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#issuecomment-922733817


   The FunctionOptions that were modified w.r.t. to positional/keyword-only args are:
   ```python
   MatchSubstringOptions(self, pattern, *, ignore_case)
   ReplaceSubstringOptions(self, pattern, replacement, *, max_replacements)
   ScalarAggregateOptions(self, *, skip_nulls, min_count)
   ModeOptions(self, n, *, skip_nulls, min_count)
   SetLookupOptions(self, value_set, *, skip_nulls)
   DayOfWeekOptions(self, *, one_based_numbering, week_start)
   NullOptions(self, *, nan_is_null)
   SplitPatternOptions(self, pattern, *, max_splits, reverse)
   ArraySortOptions(self, order)
   ```


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] pitrou commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
pitrou commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r712920339



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -569,6 +543,10 @@ cdef class FunctionOptions(_Weakrefable):
         return self.get_options().Equals(deref(other.get_options()))
 
 
+def _raise_invalid_function_option(value, description, *, error="keyword"):

Review comment:
       This will give e.g.:
   ```"foo" is not a valid count mode keyword```
   IMHO it would read better as:
   ```"foo" is not a valid count mode value```
   




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] pitrou commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
pitrou commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r712113784



##########
File path: python/pyarrow/includes/libarrow.pxd
##########
@@ -2069,10 +2076,15 @@ cdef extern from "arrow/compute/api.h" namespace "arrow::compute" nogil:
 
     cdef cppclass CMakeStructOptions \
             "arrow::compute::MakeStructOptions"(CFunctionOptions):
-        CMakeStructOptions(vector[c_string] field_names)
+        CMakeStructOptions(vector[c_string] n,
+                           vector[c_bool] r,
+                           vector[shared_ptr[const CKeyValueMetadata]] m)
+        CMakeStructOptions(vector[c_string] n)
         vector[c_string] field_names
+        vector[c_bool] field_nullability
+        vector[shared_ptr[const CKeyValueMetadata]] field_metadata
 
-    ctypedef enum CSortOrder" arrow::compute::SortOrder":
+    cdef enum CSortOrder" arrow::compute::SortOrder":

Review comment:
       It seems these `cdef` changes may have broken AppVeyor. Can you take a look?




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] pitrou commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
pitrou commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r712921002



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -980,51 +973,45 @@ cdef class _ModeOptions(FunctionOptions):
 
 
 class ModeOptions(_ModeOptions):
-    def __init__(self, n=1, skip_nulls=True, min_count=0):
+    def __init__(self, n=1, *, skip_nulls=True, min_count=0):
         self._set_options(n, skip_nulls, min_count)
 
 
 cdef class _SetLookupOptions(FunctionOptions):
-    cdef:
-        unique_ptr[CDatum] valset
-
     def _set_options(self, value_set, c_bool skip_nulls):
+        cdef unique_ptr[CDatum] valset
         if isinstance(value_set, Array):
-            self.valset.reset(new CDatum((<Array> value_set).sp_array))
+            valset.reset(new CDatum((<Array> value_set).sp_array))
         elif isinstance(value_set, ChunkedArray):
-            self.valset.reset(
-                new CDatum((<ChunkedArray> value_set).sp_chunked_array)
-            )
+            valset.reset(
+                new CDatum((<ChunkedArray> value_set).sp_chunked_array))
         elif isinstance(value_set, Scalar):
-            self.valset.reset(new CDatum((<Scalar> value_set).unwrap()))
+            valset.reset(new CDatum((<Scalar> value_set).unwrap()))
         else:
-            raise ValueError('"{}" is not a valid value_set'.format(value_set))
-
-        self.wrapped.reset(
-            new CSetLookupOptions(deref(self.valset), skip_nulls))
+            _raise_invalid_function_option(value_set, "value set",
+                                           error="type")

Review comment:
       If the type is the problem, then probably `TypeError` should be raised, not `ValueError`.




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] pitrou commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
pitrou commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r712429961



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -569,6 +543,10 @@ cdef class FunctionOptions(_Weakrefable):
         return self.get_options().Equals(deref(other.get_options()))
 
 
+def raise_invalid_function_option(value, description, *, error="keyword"):

Review comment:
       Can leave it as a free standing function.




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] edponce commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
edponce commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r713631136



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -1052,37 +1055,31 @@ cdef class _DayOfWeekOptions(FunctionOptions):
 
 
 class DayOfWeekOptions(_DayOfWeekOptions):
-    def __init__(self, one_based_numbering=False, week_start=1):
+    def __init__(self, *, one_based_numbering=False, week_start=1):
         self._set_options(one_based_numbering, week_start)
 
 
 cdef class _AssumeTimezoneOptions(FunctionOptions):
+    _ambiguous_map = {
+        "raise": CAssumeTimezoneAmbiguous_AMBIGUOUS_RAISE,
+        "earliest": CAssumeTimezoneAmbiguous_AMBIGUOUS_EARLIEST,
+        "latest": CAssumeTimezoneAmbiguous_AMBIGUOUS_LATEST,
+    }
+    _nonexistent_map = {
+        "raise": CAssumeTimezoneNonexistent_NONEXISTENT_RAISE,
+        "earliest": CAssumeTimezoneNonexistent_NONEXISTENT_EARLIEST,
+        "latest": CAssumeTimezoneNonexistent_NONEXISTENT_LATEST,
+    }
+
     def _set_options(self, timezone, ambiguous, nonexistent):
-        ambiguous_dict = {
-            'raise': CAssumeTimezoneAmbiguous_AMBIGUOUS_RAISE,
-            'earliest': CAssumeTimezoneAmbiguous_AMBIGUOUS_EARLIEST,
-            'latest': CAssumeTimezoneAmbiguous_AMBIGUOUS_LATEST,
-        }
-        nonexistent_dict = {
-            'raise': CAssumeTimezoneNonexistent_NONEXISTENT_RAISE,
-            'earliest': CAssumeTimezoneNonexistent_NONEXISTENT_EARLIEST,
-            'latest': CAssumeTimezoneNonexistent_NONEXISTENT_LATEST,
-        }
-
-        if ambiguous not in ambiguous_dict:
-            raise ValueError(
-                "{!r} is not a valid 'ambiguous' keyword".format(ambiguous)
-            )
-        if nonexistent not in nonexistent_dict:
-            raise ValueError(
-                "{!r} is not a valid 'nonexistent' keyword".format(
-                    nonexistent)
-            )
+        if ambiguous not in self._ambiguous_map:
+            _raise_invalid_function_option(ambiguous, "ambiguous")
+        if nonexistent not in self._nonexistent_map:
+            _raise_invalid_function_option(nonexistent, "nonexistent")

Review comment:
       Thanks! This change has been added.




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] edponce commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
edponce commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r713203478



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -690,99 +677,96 @@ class CastOptions(_CastOptions):
 
 
 cdef class _ElementWiseAggregateOptions(FunctionOptions):
-    def _set_options(self, bint skip_nulls):
+    def _set_options(self, skip_nulls):
         self.wrapped.reset(new CElementWiseAggregateOptions(skip_nulls))
 
 
 class ElementWiseAggregateOptions(_ElementWiseAggregateOptions):
-    def __init__(self, bint skip_nulls=True):
+    def __init__(self, *, skip_nulls=True):
         self._set_options(skip_nulls)
 
 
 cdef CRoundMode unwrap_round_mode(round_mode) except *:
-    if round_mode == 'down':
+    # TODO: Cython 0.29.x does not supports C++ scoped enums as dictionary
+    # values because they do not resolve to integers, so we use if-elses.
+    # Cython 3 fully supports C++ scoped enums resolving to integers, refer to
+    # https://cython.readthedocs.io/en/latest/src/userguide/wrapping_CPlusPlus.html#scoped-enumerations
+    if round_mode == "down":

Review comment:
       I removed comments and [created a JIRA for this.](https://issues.apache.org/jira/browse/ARROW-14058)




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] edponce commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
edponce commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r708306876



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -690,99 +700,91 @@ class CastOptions(_CastOptions):
 
 
 cdef class _ElementWiseAggregateOptions(FunctionOptions):
-    def _set_options(self, bint skip_nulls):
+    def _set_options(self, skip_nulls):
         self.wrapped.reset(new CElementWiseAggregateOptions(skip_nulls))
 
 
 class ElementWiseAggregateOptions(_ElementWiseAggregateOptions):
-    def __init__(self, bint skip_nulls=True):
+    def __init__(self, skip_nulls=True):
         self._set_options(skip_nulls)
 
 
 cdef CRoundMode unwrap_round_mode(round_mode) except *:
-    if round_mode == 'down':
-        return CRoundMode_DOWN
-    elif round_mode == 'up':
-        return CRoundMode_UP
-    elif round_mode == 'towards_zero':
-        return CRoundMode_TOWARDS_ZERO
-    elif round_mode == 'towards_infinity':
-        return CRoundMode_TOWARDS_INFINITY
-    elif round_mode == 'half_down':
-        return CRoundMode_HALF_DOWN
-    elif round_mode == 'half_up':
-        return CRoundMode_HALF_UP
-    elif round_mode == 'half_towards_zero':
-        return CRoundMode_HALF_TOWARDS_ZERO
-    elif round_mode == 'half_towards_infinity':
-        return CRoundMode_HALF_TOWARDS_INFINITY
-    elif round_mode == 'half_to_even':
-        return CRoundMode_HALF_TO_EVEN
-    elif round_mode == 'half_to_odd':
-        return CRoundMode_HALF_TO_ODD
-    else:
-        raise ValueError('"{}" is not a valid round mode'.format(round_mode))
+    round_mode_dict = {
+        "down": CRoundMode_DOWN,
+        "up": CRoundMode_UP,
+        "towards_zero": CRoundMode_TOWARDS_ZERO,
+        "towards_infinity": CRoundMode_TOWARDS_INFINITY,
+        "half_down": CRoundMode_HALF_DOWN,
+        "half_up": CRoundMode_HALF_UP,
+        "half_towards_zero": CRoundMode_HALF_TOWARDS_ZERO,
+        "half_towards_infinity": CRoundMode_HALF_TOWARDS_INFINITY,
+        "half_to_even": CRoundMode_HALF_TO_EVEN,
+        "half_to_odd": CRoundMode_HALF_TO_ODD,
+    }
+
+    if round_mode not in round_mode_dict:
+        raise ValueError(f'"{round_mode}" is not a valid round mode')
 

Review comment:
       Yes, it is missing. Thanks!




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] edponce commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
edponce commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r713549002



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -904,59 +885,71 @@ class TakeOptions(_TakeOptions):
 
 
 cdef class _PartitionNthOptions(FunctionOptions):
-    def _set_options(self, int64_t pivot):
+    def _set_options(self, pivot):
         self.wrapped.reset(new CPartitionNthOptions(pivot))
 
 
 class PartitionNthOptions(_PartitionNthOptions):
-    def __init__(self, int64_t pivot):
+    def __init__(self, pivot):
         self._set_options(pivot)
 
 
 cdef class _MakeStructOptions(FunctionOptions):
-    def _set_options(self, field_names):
+    def _set_options(self, field_names, field_nullability, field_metadata):
         cdef:
             vector[c_string] c_field_names
-        for n in field_names:
-            c_field_names.push_back(tobytes(n))
-        self.wrapped.reset(new CMakeStructOptions(c_field_names))
+            vector[shared_ptr[const CKeyValueMetadata]] c_field_metadata
+        for name in field_names:
+            c_field_names.push_back(tobytes(name))
+        for metadata in field_metadata:
+            c_field_metadata.push_back(pyarrow_unwrap_metadata(metadata))
+        self.wrapped.reset(
+            new CMakeStructOptions(c_field_names,
+                                   field_nullability,
+                                   c_field_metadata))
 
 
 class MakeStructOptions(_MakeStructOptions):
-    def __init__(self, field_names):
-        self._set_options(field_names)
+    def __init__(self, field_names, field_nullability=None,

Review comment:
       Oops, I now noticed that `MakeStructOptions` does have constructor with only the first parameter (`field_names`). I applied the suggested change (keyword-only for optional parameters).




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] edponce edited a comment on pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
edponce edited a comment on pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#issuecomment-922733817


   The FunctionOptions that were modified w.r.t. to positional/keyword-only args are:
   ```python
   MatchSubstringOptions(self, pattern, *, ignore_case)
   ReplaceSubstringOptions(self, pattern, replacement, *, max_replacements)
   ScalarAggregateOptions(self, *, skip_nulls, min_count)
   ModeOptions(self, n, *, skip_nulls, min_count)
   SetLookupOptions(self, value_set, *, skip_nulls)
   DayOfWeekOptions(self, *, one_based_numbering, week_start)
   NullOptions(self, *, nan_is_null)
   SplitPatternOptions(self, pattern, *, max_splits, reverse)
   ArraySortOptions(self, order)
   ElementWiseAggregateOptions(self, *, skip_nulls)
   QuantileOptions(self, q, *, interpolation)
   TDigestOptions(self, q, *, delta, buffer_size)
   MakeStructOptions(self, field_names, *, field_nullability, field_metadata)
   ```


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] edponce commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
edponce commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r708418292



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -899,26 +900,26 @@ cdef class _TakeOptions(FunctionOptions):
 
 
 class TakeOptions(_TakeOptions):
-    def __init__(self, *, boundscheck=True):
+    def __init__(self, boundscheck=True):

Review comment:
       I removed all the keyword arguments simply to get a code review like yours. How do we decide which options should be positional and which ones should be keyword-only?




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] jorisvandenbossche commented on pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
jorisvandenbossche commented on pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#issuecomment-923887123


   > When there is little ambiguity as to what a parameter means, there is no reason to make it keyword-only.
   >
   > @jorisvandenbossche Any thoughts on these changes?
   
   Yeah, we had a bit of discussion about it on Zulip, where the it was suggested to follow "required args -> positional, optional args -> keyword only", but so that clearly isn't a good rule, as I agree with your comments (so my initial "make a judgement call case by case based on whether you could understand it without the current" is better).
   
   > The FunctionOptions that were modified w.r.t. to positional/keyword-only args are:
   
   I think the changes listed at https://github.com/apache/arrow/pull/11147#issuecomment-922733817 all look good now.


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] jorisvandenbossche commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
jorisvandenbossche commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r712934181



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -1035,8 +1022,7 @@ class StrptimeOptions(_StrptimeOptions):
 cdef class _StrftimeOptions(FunctionOptions):
     def _set_options(self, format, locale):
         self.wrapped.reset(
-            new CStrftimeOptions(tobytes(format), tobytes(locale))
-        )
+            new CStrftimeOptions(tobytes(format), tobytes(locale)))

Review comment:
       (another styling nit: note that some formatters (eg black) will actually prefer how it was before)

##########
File path: python/pyarrow/_compute.pyx
##########
@@ -904,59 +885,71 @@ class TakeOptions(_TakeOptions):
 
 
 cdef class _PartitionNthOptions(FunctionOptions):
-    def _set_options(self, int64_t pivot):
+    def _set_options(self, pivot):
         self.wrapped.reset(new CPartitionNthOptions(pivot))
 
 
 class PartitionNthOptions(_PartitionNthOptions):
-    def __init__(self, int64_t pivot):
+    def __init__(self, pivot):
         self._set_options(pivot)
 
 
 cdef class _MakeStructOptions(FunctionOptions):
-    def _set_options(self, field_names):
+    def _set_options(self, field_names, field_nullability, field_metadata):
         cdef:
             vector[c_string] c_field_names
-        for n in field_names:
-            c_field_names.push_back(tobytes(n))
-        self.wrapped.reset(new CMakeStructOptions(c_field_names))
+            vector[shared_ptr[const CKeyValueMetadata]] c_field_metadata
+        for name in field_names:
+            c_field_names.push_back(tobytes(name))
+        for metadata in field_metadata:
+            c_field_metadata.push_back(pyarrow_unwrap_metadata(metadata))
+        self.wrapped.reset(
+            new CMakeStructOptions(c_field_names,
+                                   field_nullability,
+                                   c_field_metadata))
 
 
 class MakeStructOptions(_MakeStructOptions):
-    def __init__(self, field_names):
-        self._set_options(field_names)
+    def __init__(self, field_names, field_nullability=None,

Review comment:
       ```suggestion
       def __init__(self, field_names, *, field_nullability=None,
   ```
   
   ?

##########
File path: python/pyarrow/compute.py
##########
@@ -656,8 +673,13 @@ def top_k_unstable(values, k, sort_keys=None, memory_pool=None):
     Parameters
     ----------
     values : Array, ChunkedArray, RecordBatch, or Table
-    k :  The number of `k` elements to keep.
-    sort_keys : Column key names to order by when input is table-like data.
+        Data to sort and get top indices from.
+    k : int
+        The number of `k` elements to keep.
+    sort_keys : List or tuple

Review comment:
       ```suggestion
       sort_keys : list
   ```
   
   Or "list-like" in you prefer. Since it supports any sequence, I don't think it's needed to specifically mention "tuple" in addition to list.
   
   (reason this catched my attention is actually because I first misread it as "list of tuple", while `sort_keys` in general follow that structure, while here it should be just be a list of strings)

##########
File path: python/pyarrow/compute.py
##########
@@ -697,8 +719,13 @@ def bottom_k_unstable(values, k, sort_keys=None, memory_pool=None):
     Parameters
     ----------
     values : Array, ChunkedArray, RecordBatch, or Table
-    k :  The number of `k` elements to keep.
-    sort_keys : Column key names to order by when input is table-like data.
+        Data to sort and get bottom indices from.
+    k : int
+        The number of `k` elements to keep.
+    sort_keys : List or tuple

Review comment:
       ```suggestion
       sort_keys : list
   ```

##########
File path: python/pyarrow/_compute.pyx
##########
@@ -327,23 +317,17 @@ cdef class Function(_Weakrefable):
             CExecContext c_exec_ctx = CExecContext(pool)
             vector[CDatum] c_args
             CDatum result
-
         _pack_compute_args(args, &c_args)
-
         if options is not None:
             c_options = options.get_options()
-

Review comment:
       A small nit (and you don't have to change it back, but just noting because you are doing quite some styling-only changes), but personally I don't think removing all those whitespace lines necessarily improves readability ..

##########
File path: python/pyarrow/_compute.pyx
##########
@@ -1131,122 +1106,97 @@ cdef class _SplitPatternOptions(FunctionOptions):
 
 
 class SplitPatternOptions(_SplitPatternOptions):
-    def __init__(self, *, pattern, max_splits=-1, reverse=False):
+    def __init__(self, pattern, *, max_splits=-1, reverse=False):
         self._set_options(pattern, max_splits, reverse)
 
 
+cdef CSortOrder unwrap_sort_order(order) except *:
+    # TODO: Cython 0.29.x does not supports C++ scoped enums as dictionary
+    # values because they do not resolve to integers, so we use if-elses.
+    # Cython 3 supports C++ scoped enums resolving to integers, refer to
+    # https://cython.readthedocs.io/en/latest/src/userguide/wrapping_CPlusPlus.html#scoped-enumerations
+    if order == "ascending":
+        return CSortOrder_Ascending
+    elif order == "descending":
+        return CSortOrder_Descending
+    _raise_invalid_function_option(order, "sort order")
+
+
 cdef class _ArraySortOptions(FunctionOptions):
     def _set_options(self, order):
-        if order == "ascending":
-            self.wrapped.reset(new CArraySortOptions(CSortOrder_Ascending))
-        elif order == "descending":
-            self.wrapped.reset(new CArraySortOptions(CSortOrder_Descending))
-        else:
-            raise ValueError(
-                "{!r} is not a valid order".format(order)
-            )
+        self.wrapped.reset(new CArraySortOptions(unwrap_sort_order(order)))
 
 
 class ArraySortOptions(_ArraySortOptions):
-    def __init__(self, *, order='ascending'):
+    def __init__(self, order="ascending"):
         self._set_options(order)
 
 
 cdef class _SortOptions(FunctionOptions):
     def _set_options(self, sort_keys):
-        cdef:
-            vector[CSortKey] c_sort_keys
-            c_string c_name
-            CSortOrder c_order
-
+        cdef vector[CSortKey] c_sort_keys
         for name, order in sort_keys:
-            if order == "ascending":
-                c_order = CSortOrder_Ascending
-            elif order == "descending":
-                c_order = CSortOrder_Descending
-            else:
-                raise ValueError(
-                    "{!r} is not a valid order".format(order)
-                )
-            c_name = tobytes(name)
-            c_sort_keys.push_back(CSortKey(c_name, c_order))
-
+            c_sort_keys.push_back(CSortKey(tobytes(name),
+                                  unwrap_sort_order(order)))
         self.wrapped.reset(new CSortOptions(c_sort_keys))
 
 
 class SortOptions(_SortOptions):
-    def __init__(self, sort_keys=None):
-        if sort_keys is None:
-            sort_keys = []
+    def __init__(self, sort_keys):
         self._set_options(sort_keys)
 
 
 cdef class _SelectKOptions(FunctionOptions):
     def _set_options(self, k, sort_keys):
-        cdef:
-            c_string c_name
-            vector[CSortKey] c_sort_keys
-            CSortOrder c_order
-
+        cdef vector[CSortKey] c_sort_keys
         for name, order in sort_keys:
-            if order == "ascending":
-                c_order = CSortOrder_Ascending
-            elif order == "descending":
-                c_order = CSortOrder_Descending
-            else:
-                raise ValueError(
-                    "{!r} is not a valid order".format(order)
-                )
-            c_name = tobytes(name)
-            c_sort_keys.push_back(CSortKey(c_name, c_order))
-
+            c_sort_keys.push_back(CSortKey(tobytes(name),
+                                  unwrap_sort_order(order)))
         self.wrapped.reset(new CSelectKOptions(k, c_sort_keys))
 
 
 class SelectKOptions(_SelectKOptions):
-    def __init__(self, k, sort_keys=None):
-        if sort_keys is None:
-            sort_keys = []
+    def __init__(self, k, sort_keys):
         self._set_options(k, sort_keys)
 
 
 cdef class _QuantileOptions(FunctionOptions):
+    _interp_map = {
+        "linear": CQuantileInterp_LINEAR,
+        "lower": CQuantileInterp_LOWER,
+        "higher": CQuantileInterp_HIGHER,
+        "nearest": CQuantileInterp_NEAREST,
+        "midpoint": CQuantileInterp_MIDPOINT,
+    }
+
     def _set_options(self, quantiles, interp, skip_nulls, min_count):
-        interp_dict = {
-            'linear': CQuantileInterp_LINEAR,
-            'lower': CQuantileInterp_LOWER,
-            'higher': CQuantileInterp_HIGHER,
-            'nearest': CQuantileInterp_NEAREST,
-            'midpoint': CQuantileInterp_MIDPOINT,
-        }
-        if interp not in interp_dict:
-            raise ValueError(
-                '{!r} is not a valid interpolation'
-                .format(interp))
-        self.wrapped.reset(
-            new CQuantileOptions(quantiles, interp_dict[interp],
-                                 skip_nulls, min_count))
+        try:
+            self.wrapped.reset(
+                new CQuantileOptions(quantiles, self._interp_map[interp],
+                                     skip_nulls, min_count))
+        except KeyError:
+            _raise_invalid_function_option(interp, "quantile interpolation")
 
 
 class QuantileOptions(_QuantileOptions):
-    def __init__(self, *, q=0.5, interpolation='linear',
-                 skip_nulls=True, min_count=0):
+    def __init__(self, *, q=0.5, interpolation="linear", skip_nulls=True,

Review comment:
       ```suggestion
       def __init__(self, q=0.5, *, interpolation="linear", skip_nulls=True,
   ```
   
   ? 
   
   (since `q` is not a very descriptive keyword name anyway, it's not necessarily useful to have to spell it out)

##########
File path: python/pyarrow/_compute.pyx
##########
@@ -569,6 +543,10 @@ cdef class FunctionOptions(_Weakrefable):
         return self.get_options().Equals(deref(other.get_options()))
 
 
+def _raise_invalid_function_option(value, description, *, error="keyword"):

Review comment:
       Or could also leave out the final word entirely: `"foo" is not a valid count mode`




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] pitrou commented on a change in pull request #11147: ARROW-13327: [C++][Python] Improve consistency of explicit C++ types in PyArrow files

Posted by GitBox <gi...@apache.org>.
pitrou commented on a change in pull request #11147:
URL: https://github.com/apache/arrow/pull/11147#discussion_r709915241



##########
File path: python/pyarrow/_compute.pyx
##########
@@ -284,18 +283,9 @@ cdef class Function(_Weakrefable):
         The function kind.
         """
         cdef FunctionKind c_kind = self.base_func.kind()
-        if c_kind == FunctionKind_SCALAR:
-            return 'scalar'
-        elif c_kind == FunctionKind_VECTOR:
-            return 'vector'
-        elif c_kind == FunctionKind_SCALAR_AGGREGATE:
-            return 'scalar_aggregate'
-        elif c_kind == FunctionKind_HASH_AGGREGATE:
-            return 'hash_aggregate'
-        elif c_kind == FunctionKind_META:
-            return 'meta'
-        else:
+        if c_kind not in type(self).kind_dict:
             raise NotImplementedError("Unknown Function::Kind")
+        return type(self).kind_dict[c_kind]

Review comment:
       ```python
   try:
       return self.kind_dict[c_kind]
   except KeyError:
       raise NotImplementedError("Unknown Function::Kind")
   ```

##########
File path: python/pyarrow/_compute.pyx
##########
@@ -792,7 +775,7 @@ cdef class _PadOptions(FunctionOptions):
 
 
 class PadOptions(_PadOptions):
-    def __init__(self, width, padding=' '):
+    def __init__(self, width, *, padding=" "):

Review comment:
       Similarly, this doesn't seem desirable. I don't think there's any ambiguity as to what the second argument is.

##########
File path: python/pyarrow/_compute.pyx
##########
@@ -690,99 +678,94 @@ class CastOptions(_CastOptions):
 
 
 cdef class _ElementWiseAggregateOptions(FunctionOptions):
-    def _set_options(self, bint skip_nulls):
+    def _set_options(self, skip_nulls):
         self.wrapped.reset(new CElementWiseAggregateOptions(skip_nulls))
 
 
 class ElementWiseAggregateOptions(_ElementWiseAggregateOptions):
-    def __init__(self, bint skip_nulls=True):
+    def __init__(self, *, skip_nulls=True):
         self._set_options(skip_nulls)
 
 
 cdef CRoundMode unwrap_round_mode(round_mode) except *:
-    if round_mode == 'down':
+    # Explicit if-else since Cython does not supports storing C++ enum classes
+    # as dictionary values because they do not resolve to integers.
+    if round_mode == "down":
         return CRoundMode_DOWN
-    elif round_mode == 'up':
+    elif round_mode == "up":
         return CRoundMode_UP
-    elif round_mode == 'towards_zero':
+    elif round_mode == "towards_zero":
         return CRoundMode_TOWARDS_ZERO
-    elif round_mode == 'towards_infinity':
+    elif round_mode == "towards_infinity":
         return CRoundMode_TOWARDS_INFINITY
-    elif round_mode == 'half_down':
+    elif round_mode == "half_down":
         return CRoundMode_HALF_DOWN
-    elif round_mode == 'half_up':
+    elif round_mode == "half_up":
         return CRoundMode_HALF_UP
-    elif round_mode == 'half_towards_zero':
+    elif round_mode == "half_towards_zero":
         return CRoundMode_HALF_TOWARDS_ZERO
-    elif round_mode == 'half_towards_infinity':
+    elif round_mode == "half_towards_infinity":
         return CRoundMode_HALF_TOWARDS_INFINITY
-    elif round_mode == 'half_to_even':
+    elif round_mode == "half_to_even":
         return CRoundMode_HALF_TO_EVEN
-    elif round_mode == 'half_to_odd':
+    elif round_mode == "half_to_odd":
         return CRoundMode_HALF_TO_ODD
     else:
-        raise ValueError('"{}" is not a valid round mode'.format(round_mode))
+        raise ValueError(f"\"{round_mode}\" is not a valid 'round mode'")
 
 
 cdef class _RoundOptions(FunctionOptions):
-    def _set_options(self, int64_t ndigits, round_mode):
-        cdef:
-            CRoundMode c_round_mode = CRoundMode_HALF_TO_EVEN
-        c_round_mode = unwrap_round_mode(round_mode)
-        self.wrapped.reset(new CRoundOptions(ndigits, c_round_mode))
+    def _set_options(self, ndigits, round_mode):
+        self.wrapped.reset(new CRoundOptions(ndigits,
+                                             unwrap_round_mode(round_mode)))
 
 
 class RoundOptions(_RoundOptions):
-    def __init__(self, ndigits=0, round_mode='half_to_even'):
+    def __init__(self, *, ndigits=0, round_mode="half_to_even"):

Review comment:
       This change doesn't look desirable to me. The Python build-in [round](https://docs.python.org/3/library/functions.html#round) function takes  positional arguments.

##########
File path: python/pyarrow/_compute.pyx
##########
@@ -236,10 +226,19 @@ cdef class Function(_Weakrefable):
 
     * "meta" functions dispatch to other functions.
     """
+
     cdef:
         shared_ptr[CFunction] sp_func
         CFunction* base_func
 
+    kind_dict = {

Review comment:
       Call this `_kind_dict`? This isn't a public API.

##########
File path: python/pyarrow/_compute.pyx
##########
@@ -844,53 +823,53 @@ class ExtractRegexOptions(_ExtractRegexOptions):
 
 
 cdef class _SliceOptions(FunctionOptions):
-    def _set_options(self, int64_t start, int64_t stop, int64_t step):
+    def _set_options(self, start, stop, step):
         self.wrapped.reset(new CSliceOptions(start, stop, step))
 
 
 class SliceOptions(_SliceOptions):
-    def __init__(self, int64_t start, int64_t stop=sys.maxsize,
-                 int64_t step=1):
+    def __init__(self, start, *, stop=sys.maxsize, step=1):

Review comment:
       Same here. Why would `stop` be a keyword-only parameter?

##########
File path: python/pyarrow/_compute.pyx
##########
@@ -690,99 +678,94 @@ class CastOptions(_CastOptions):
 
 
 cdef class _ElementWiseAggregateOptions(FunctionOptions):
-    def _set_options(self, bint skip_nulls):
+    def _set_options(self, skip_nulls):
         self.wrapped.reset(new CElementWiseAggregateOptions(skip_nulls))
 
 
 class ElementWiseAggregateOptions(_ElementWiseAggregateOptions):
-    def __init__(self, bint skip_nulls=True):
+    def __init__(self, *, skip_nulls=True):
         self._set_options(skip_nulls)
 
 
 cdef CRoundMode unwrap_round_mode(round_mode) except *:
-    if round_mode == 'down':
+    # Explicit if-else since Cython does not supports storing C++ enum classes
+    # as dictionary values because they do not resolve to integers.
+    if round_mode == "down":
         return CRoundMode_DOWN
-    elif round_mode == 'up':
+    elif round_mode == "up":
         return CRoundMode_UP
-    elif round_mode == 'towards_zero':
+    elif round_mode == "towards_zero":
         return CRoundMode_TOWARDS_ZERO
-    elif round_mode == 'towards_infinity':
+    elif round_mode == "towards_infinity":
         return CRoundMode_TOWARDS_INFINITY
-    elif round_mode == 'half_down':
+    elif round_mode == "half_down":
         return CRoundMode_HALF_DOWN
-    elif round_mode == 'half_up':
+    elif round_mode == "half_up":
         return CRoundMode_HALF_UP
-    elif round_mode == 'half_towards_zero':
+    elif round_mode == "half_towards_zero":
         return CRoundMode_HALF_TOWARDS_ZERO
-    elif round_mode == 'half_towards_infinity':
+    elif round_mode == "half_towards_infinity":
         return CRoundMode_HALF_TOWARDS_INFINITY
-    elif round_mode == 'half_to_even':
+    elif round_mode == "half_to_even":
         return CRoundMode_HALF_TO_EVEN
-    elif round_mode == 'half_to_odd':
+    elif round_mode == "half_to_odd":
         return CRoundMode_HALF_TO_ODD
     else:
-        raise ValueError('"{}" is not a valid round mode'.format(round_mode))
+        raise ValueError(f"\"{round_mode}\" is not a valid 'round mode'")
 
 
 cdef class _RoundOptions(FunctionOptions):
-    def _set_options(self, int64_t ndigits, round_mode):
-        cdef:
-            CRoundMode c_round_mode = CRoundMode_HALF_TO_EVEN
-        c_round_mode = unwrap_round_mode(round_mode)
-        self.wrapped.reset(new CRoundOptions(ndigits, c_round_mode))
+    def _set_options(self, ndigits, round_mode):
+        self.wrapped.reset(new CRoundOptions(ndigits,
+                                             unwrap_round_mode(round_mode)))
 
 
 class RoundOptions(_RoundOptions):
-    def __init__(self, ndigits=0, round_mode='half_to_even'):
+    def __init__(self, *, ndigits=0, round_mode="half_to_even"):
         self._set_options(ndigits, round_mode)
 
 
 cdef class _RoundToMultipleOptions(FunctionOptions):
-    def _set_options(self, double multiple, round_mode):
-        cdef:
-            CRoundMode c_round_mode = CRoundMode_HALF_TO_EVEN
-        c_round_mode = unwrap_round_mode(round_mode)
-        self.wrapped.reset(new CRoundToMultipleOptions(multiple, c_round_mode))
+    def _set_options(self, multiple, round_mode):
+        self.wrapped.reset(
+            new CRoundToMultipleOptions(multiple,
+                                        unwrap_round_mode(round_mode)))
 
 
 class RoundToMultipleOptions(_RoundToMultipleOptions):
-    def __init__(self, multiple=1.0, round_mode='half_to_even'):
+    def __init__(self, *, multiple=1.0, round_mode="half_to_even"):

Review comment:
       Similarly, this change doesn't look desirable.

##########
File path: python/pyarrow/_compute.pyx
##########
@@ -980,51 +958,43 @@ cdef class _ModeOptions(FunctionOptions):
 
 
 class ModeOptions(_ModeOptions):
-    def __init__(self, n=1, skip_nulls=True, min_count=0):
+    def __init__(self, *, n=1, skip_nulls=True, min_count=0):

Review comment:
       `n` could very well be positional.

##########
File path: python/pyarrow/_compute.pyx
##########
@@ -844,53 +823,53 @@ class ExtractRegexOptions(_ExtractRegexOptions):
 
 
 cdef class _SliceOptions(FunctionOptions):
-    def _set_options(self, int64_t start, int64_t stop, int64_t step):
+    def _set_options(self, start, stop, step):
         self.wrapped.reset(new CSliceOptions(start, stop, step))
 
 
 class SliceOptions(_SliceOptions):
-    def __init__(self, int64_t start, int64_t stop=sys.maxsize,
-                 int64_t step=1):
+    def __init__(self, start, *, stop=sys.maxsize, step=1):
         self._set_options(start, stop, step)
 
 
 cdef class _FilterOptions(FunctionOptions):
+    null_selection_dict = {
+        "drop": CFilterNullSelectionBehavior_DROP,
+        "emit_null": CFilterNullSelectionBehavior_EMIT_NULL,
+    }
+
     def _set_options(self, null_selection_behavior):
-        if null_selection_behavior == 'drop':
-            self.wrapped.reset(
-                new CFilterOptions(CFilterNullSelectionBehavior_DROP))
-        elif null_selection_behavior == 'emit_null':
-            self.wrapped.reset(
-                new CFilterOptions(CFilterNullSelectionBehavior_EMIT_NULL))
-        else:
-            raise ValueError(
-                '"{}" is not a valid null_selection_behavior'
-                .format(null_selection_behavior))
+        if null_selection_behavior not in type(self).null_selection_dict:
+            raise ValueError(f"\"{null_selection_behavior}\""
+                             "is not a valid 'null selection behavior'")
+        self.wrapped.reset(
+            new CFilterOptions(
+                type(self).null_selection_dict[null_selection_behavior]))
 
 
 class FilterOptions(_FilterOptions):
-    def __init__(self, null_selection_behavior='drop'):
+    def __init__(self, *, null_selection_behavior="drop"):

Review comment:
       Having to type `null_selection_behavior` is rather annoying... 

##########
File path: python/pyarrow/_compute.pyx
##########
@@ -844,53 +823,53 @@ class ExtractRegexOptions(_ExtractRegexOptions):
 
 
 cdef class _SliceOptions(FunctionOptions):
-    def _set_options(self, int64_t start, int64_t stop, int64_t step):
+    def _set_options(self, start, stop, step):
         self.wrapped.reset(new CSliceOptions(start, stop, step))
 
 
 class SliceOptions(_SliceOptions):
-    def __init__(self, int64_t start, int64_t stop=sys.maxsize,
-                 int64_t step=1):
+    def __init__(self, start, *, stop=sys.maxsize, step=1):
         self._set_options(start, stop, step)
 
 
 cdef class _FilterOptions(FunctionOptions):
+    null_selection_dict = {

Review comment:
       `_null_selection_dict`

##########
File path: python/pyarrow/_compute.pyx
##########
@@ -929,34 +907,34 @@ class MakeStructOptions(_MakeStructOptions):
 
 cdef class _ScalarAggregateOptions(FunctionOptions):
     def _set_options(self, skip_nulls, min_count):
-        self.wrapped.reset(
-            new CScalarAggregateOptions(skip_nulls, min_count))
+        self.wrapped.reset(new CScalarAggregateOptions(skip_nulls, min_count))
 
 
 class ScalarAggregateOptions(_ScalarAggregateOptions):
-    def __init__(self, skip_nulls=True, min_count=1):
+    def __init__(self, *, skip_nulls=True, min_count=1):
         self._set_options(skip_nulls, min_count)
 
 
 cdef class _CountOptions(FunctionOptions):
+    mode_dict = {
+        "only_valid": CCountMode_ONLY_VALID,
+        "only_null": CCountMode_ONLY_NULL,
+        "all": CCountMode_ALL,
+    }
+
     def _set_options(self, mode):
-        if mode == 'only_valid':
-            self.wrapped.reset(new CCountOptions(CCountMode_ONLY_VALID))
-        elif mode == 'only_null':
-            self.wrapped.reset(new CCountOptions(CCountMode_ONLY_NULL))
-        elif mode == 'all':
-            self.wrapped.reset(new CCountOptions(CCountMode_ALL))
-        else:
-            raise ValueError(f'"{mode}" is not a valid mode')
+        if mode not in type(self).mode_dict:
+            raise ValueError(f"\"{mode}\" is not a valid 'count mode'")
+        self.wrapped.reset(new CCountOptions(type(self).mode_dict[mode]))
 
 
 class CountOptions(_CountOptions):
-    def __init__(self, mode='only_valid'):
+    def __init__(self, *, mode="only_valid"):

Review comment:
       Making this keyword-only doesn't seem useful, IMHO.

##########
File path: python/pyarrow/_compute.pyx
##########
@@ -1131,106 +1092,83 @@ cdef class _SplitPatternOptions(FunctionOptions):
 
 
 class SplitPatternOptions(_SplitPatternOptions):
-    def __init__(self, *, pattern, max_splits=-1, reverse=False):
+    def __init__(self, pattern, *, max_splits=-1, reverse=False):
         self._set_options(pattern, max_splits, reverse)
 
 
+cdef CSortOrder unwrap_sort_order(order) except *:
+    # Explicit if-else since Cython does not supports storing C++ enum classes
+    # as dictionary values because they do not resolve to integers.
+    if order == "ascending":
+        return CSortOrder_Ascending
+    elif order == "descending":
+        return CSortOrder_Descending
+    else:
+        raise ValueError(f'"{order}" is not a valid order')
+
+
 cdef class _ArraySortOptions(FunctionOptions):
     def _set_options(self, order):
-        if order == "ascending":
-            self.wrapped.reset(new CArraySortOptions(CSortOrder_Ascending))
-        elif order == "descending":
-            self.wrapped.reset(new CArraySortOptions(CSortOrder_Descending))
-        else:
-            raise ValueError(
-                "{!r} is not a valid order".format(order)
-            )
+        self.wrapped.reset(new CArraySortOptions(unwrap_sort_order(order)))
 
 
 class ArraySortOptions(_ArraySortOptions):
-    def __init__(self, *, order='ascending'):
+    def __init__(self, *, order="ascending"):
         self._set_options(order)
 
 
 cdef class _SortOptions(FunctionOptions):
     def _set_options(self, sort_keys):
-        cdef:
-            vector[CSortKey] c_sort_keys
-            c_string c_name
-            CSortOrder c_order
-
+        cdef vector[CSortKey] c_sort_keys
         for name, order in sort_keys:
-            if order == "ascending":
-                c_order = CSortOrder_Ascending
-            elif order == "descending":
-                c_order = CSortOrder_Descending
-            else:
-                raise ValueError(
-                    "{!r} is not a valid order".format(order)
-                )
-            c_name = tobytes(name)
-            c_sort_keys.push_back(CSortKey(c_name, c_order))
-
+            c_sort_keys.push_back(CSortKey(tobytes(name),
+                                  unwrap_sort_order(order)))
         self.wrapped.reset(new CSortOptions(c_sort_keys))
 
 
 class SortOptions(_SortOptions):
-    def __init__(self, sort_keys=None):
+    def __init__(self, *, sort_keys=None):
         if sort_keys is None:
             sort_keys = []
         self._set_options(sort_keys)
 
 
 cdef class _SelectKOptions(FunctionOptions):
     def _set_options(self, k, sort_keys):
-        cdef:
-            c_string c_name
-            vector[CSortKey] c_sort_keys
-            CSortOrder c_order
-
+        cdef vector[CSortKey] c_sort_keys
         for name, order in sort_keys:
-            if order == "ascending":
-                c_order = CSortOrder_Ascending
-            elif order == "descending":
-                c_order = CSortOrder_Descending
-            else:
-                raise ValueError(
-                    "{!r} is not a valid order".format(order)
-                )
-            c_name = tobytes(name)
-            c_sort_keys.push_back(CSortKey(c_name, c_order))
-
+            c_sort_keys.push_back(CSortKey(tobytes(name),
+                                  unwrap_sort_order(order)))
         self.wrapped.reset(new CSelectKOptions(k, c_sort_keys))
 
 
 class SelectKOptions(_SelectKOptions):
-    def __init__(self, k, sort_keys=None):
+    def __init__(self, *, k=-1, sort_keys=None):

Review comment:
       Well, it should be clear that the first argument to `select_k` is the `k` number, no?

##########
File path: python/pyarrow/_compute.pyx
##########
@@ -1131,106 +1092,83 @@ cdef class _SplitPatternOptions(FunctionOptions):
 
 
 class SplitPatternOptions(_SplitPatternOptions):
-    def __init__(self, *, pattern, max_splits=-1, reverse=False):
+    def __init__(self, pattern, *, max_splits=-1, reverse=False):
         self._set_options(pattern, max_splits, reverse)
 
 
+cdef CSortOrder unwrap_sort_order(order) except *:
+    # Explicit if-else since Cython does not supports storing C++ enum classes
+    # as dictionary values because they do not resolve to integers.
+    if order == "ascending":
+        return CSortOrder_Ascending
+    elif order == "descending":
+        return CSortOrder_Descending
+    else:
+        raise ValueError(f'"{order}" is not a valid order')
+
+
 cdef class _ArraySortOptions(FunctionOptions):
     def _set_options(self, order):
-        if order == "ascending":
-            self.wrapped.reset(new CArraySortOptions(CSortOrder_Ascending))
-        elif order == "descending":
-            self.wrapped.reset(new CArraySortOptions(CSortOrder_Descending))
-        else:
-            raise ValueError(
-                "{!r} is not a valid order".format(order)
-            )
+        self.wrapped.reset(new CArraySortOptions(unwrap_sort_order(order)))
 
 
 class ArraySortOptions(_ArraySortOptions):
-    def __init__(self, *, order='ascending'):
+    def __init__(self, *, order="ascending"):
         self._set_options(order)
 
 
 cdef class _SortOptions(FunctionOptions):
     def _set_options(self, sort_keys):
-        cdef:
-            vector[CSortKey] c_sort_keys
-            c_string c_name
-            CSortOrder c_order
-
+        cdef vector[CSortKey] c_sort_keys
         for name, order in sort_keys:
-            if order == "ascending":
-                c_order = CSortOrder_Ascending
-            elif order == "descending":
-                c_order = CSortOrder_Descending
-            else:
-                raise ValueError(
-                    "{!r} is not a valid order".format(order)
-                )
-            c_name = tobytes(name)
-            c_sort_keys.push_back(CSortKey(c_name, c_order))
-
+            c_sort_keys.push_back(CSortKey(tobytes(name),
+                                  unwrap_sort_order(order)))
         self.wrapped.reset(new CSortOptions(c_sort_keys))
 
 
 class SortOptions(_SortOptions):
-    def __init__(self, sort_keys=None):
+    def __init__(self, *, sort_keys=None):

Review comment:
       Similarly, this doesn't seem to increase usability or readability.
   




-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org