Yicong-Huang commented on code in PR #54125:
URL: https://github.com/apache/spark/pull/54125#discussion_r2776493226
##########
python/pyspark/sql/conversion.py:
##########
@@ -159,6 +159,246 @@ def to_pandas(
]
+def cast_arrow_array(
+ arr: "pa.Array",
+ target_type: "pa.DataType",
+ *,
+ safe: bool = True,
+ allow_cast: bool = True,
+ error_class: Optional[str] = None,
+) -> "pa.Array":
+ """
+ Cast an Arrow Array to a target type.
+
+ Parameters
+ ----------
+ arr : pa.Array
+ Input Arrow array
+ target_type : pa.DataType
+ Target Arrow type
+ safe : bool
+ Whether to use safe casting (default True)
+ allow_cast : bool
+ Whether to allow casting when types don't match (default True)
+ error_class : str, optional
+ Custom error class for type mismatch errors
+
+ Returns
+ -------
+ pa.Array
+ """
+ import pyarrow as pa
+
+ from pyspark.errors import PySparkRuntimeError, PySparkTypeError
+
+ if arr.type == target_type:
+ return arr
+
+ if not allow_cast:
+ raise PySparkTypeError(
+ "Arrow UDFs require the return type to match the expected Arrow
type. "
+ f"Expected: {target_type}, but got: {arr.type}."
+ )
+
+ try:
+ return arr.cast(target_type=target_type, safe=safe)
+ except (pa.ArrowInvalid, pa.ArrowTypeError):
+ if error_class:
+ raise PySparkRuntimeError(
+ errorClass=error_class,
+ messageParameters={
+ "expected": str(target_type),
+ "actual": str(arr.type),
Review Comment:
that is unfortunately the current behavior. I would prefer to keep it the
same for this PR, we can definitely improve it later.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]