lidavidm commented on code in PR #12590:
URL: https://github.com/apache/arrow/pull/12590#discussion_r848976167


##########
python/pyarrow/_compute.pyx:
##########
@@ -2251,3 +2325,158 @@ cdef CExpression _bind(Expression filter, Schema 
schema) except *:
 
     return GetResultValue(filter.unwrap().Bind(
         deref(pyarrow_unwrap_schema(schema).get())))
+
+
+cdef CFunctionDoc _make_function_doc(dict func_doc) except *:
+    """
+    Helper function to generate the FunctionDoc
+    """
+    cdef:
+        CFunctionDoc f_doc
+        vector[c_string] c_arg_names
+        c_bool c_options_required
+
+    validate_expr = "summary" in func_doc.keys(
+    ) and "description" in func_doc.keys() and "arg_names" in func_doc.keys()
+    if not validate_expr:
+        raise ValueError(
+            "function doc dictionary must contain, summary, arg_names and a 
description")
+    f_doc.summary = tobytes(func_doc["summary"])
+    f_doc.description = tobytes(func_doc["description"])
+    for arg_name in func_doc["arg_names"]:
+        c_arg_names.push_back(tobytes(arg_name))
+    f_doc.arg_names = c_arg_names
+    # UDFOptions integration:
+    # TODO: https://issues.apache.org/jira/browse/ARROW-16041
+    f_doc.options_class = tobytes("None")
+    c_options_required = False
+    f_doc.options_required = c_options_required
+    return f_doc
+
+
+def register_scalar_function(func_name, num_args, function_doc, in_types,
+                             out_type, function):
+    """
+    Register a user-defined-function.
+
+    Parameters
+    ----------
+
+    func_name : str
+        Name of the function. This name must be globally unique. 
+    num_args : int
+       Number of arguments in the function.
+       When defining a function with variable arguments, 
+       the num_args represents the minimum number of arguments
+       required. 
+    function_doc : dict
+        A dictionary object with keys "summary" (str),
+        "description" (str), and "arg_names" (list of str).
+    in_types : List[InputType]
+        List of InputType objects which defines the input 
+        types for the function. When defining a list of InputType
+        for a varargs function, the list only needs to contain the
+        number of elements equal to the num_args (which is the miniumu
+        required arguments).
+    out_type : DataType
+        Output type of the function.
+    function : callable
+        User-defined-function
+        function includes arguments equal to the number
+        of input_types defined. The return type of the 
+        function is of the type defined as output_type. 
+        The output should be an Array, Scalar, ChunkedArray,
+        Table, or RecordBatch based on the out_type.
+
+    Example
+    -------
+
+    >>> from pyarrow import compute as pc
+    >>> from pyarrow.compute import register_scalar_function
+    >>> from pyarrow.compute import InputType
+    >>> 
+    >>> func_doc = {}
+    >>> func_doc["summary"] = "simple udf"
+    >>> func_doc["description"] = "add a constant to a scalar"
+    >>> func_doc["arg_names"] = ["x"]
+    >>> 
+    >>> def add_constant(array):
+    ...     return pc.call_function("add", [array, 1])
+    ... 
+    >>> 
+    >>> func_name = "py_add_func"
+    >>> arity = 1
+    >>> in_types = [InputType.array(pa.int64())]
+    >>> out_type = pa.int64()
+    >>> register_function(func_name, arity, func_doc,
+    ...                   in_types, out_type, add_constant)
+    >>> 
+    >>> func = pc.get_function(func_name)
+    >>> func.name
+    'py_add_func'
+    >>> ans = pc.call_function(func_name, [pa.array([20])])
+    >>> ans
+    <pyarrow.lib.Int64Array object at 0x10c22e700>
+    [
+    21
+    ]
+    """
+    cdef:
+        c_string c_func_name
+        CArity c_arity
+        CFunctionDoc c_func_doc
+        CInputType in_tmp
+        vector[CInputType] c_in_types
+        PyObject* c_function
+        shared_ptr[CDataType] c_type
+        COutputType* c_out_type
+        CScalarUdfBuilder* c_sc_builder
+        CStatus st
+        CScalarUdfOptions* c_options
+
+    c_func_name = tobytes(func_name)
+
+    if callable(function):
+        c_function = <PyObject*>function
+    else:
+        raise ValueError("Object must be a callable")
+
+    func_spec = inspect.getfullargspec(function)
+    if func_spec.varargs:
+        if num_args <= 0:
+            raise ValueError("number of arguments must be >= 0")
+        c_arity = CArity.VarArgs(num_args)
+    else:
+        if num_args <= 0:
+            raise ValueError("number of arguments must be >= 0")
+        if num_args == 0:
+            c_arity = CArity.Nullary()
+        elif num_args == 1:
+            c_arity = CArity.Unary()
+        elif num_args == 2:
+            c_arity = CArity.Binary()
+        elif num_args == 3:
+            c_arity = CArity.Ternary()
+
+    c_func_doc = _make_function_doc(function_doc)
+
+    if in_types and isinstance(in_types, list):
+        for in_type in in_types:
+            in_tmp = (<InputType> in_type).input_type
+            c_in_types.push_back(in_tmp)
+    else:
+        raise ValueError("input types must be of type InputType")

Review Comment:
   Python is not so strictly typed. A user might expect to pass in a tuple at 
the very least.
   
   However, the code has changed since then and `dict` is the only reasonable 
type. In general, however, `isinstance` is likely a code smell in Python. Just 
use the value and let Python raise an exception if it does not "work" (duck 
typing). If you are going to raise an exception yourself, at least make sure it 
is TypeError and make sure your error message is actually correct.



-- 
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-unsubscr...@arrow.apache.org

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

Reply via email to