You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by ru...@apache.org on 2026/10/20 08:35:07 UTC

(spark) branch master updated: [SPARK-60173][PYTHON][TEST] Replace type: ignore[union-attr] in pyspark.ml

This is an automated email from the ASF dual-hosted git repository.

zhengruifeng pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/master by this push:
     new c5bec12e27b5 [SPARK-60173][PYTHON][TEST] Replace type: ignore[union-attr] in pyspark.ml
c5bec12e27b5 is described below

commit c5bec12e27b5001d8bdefcff8a6f1fa08bfa6a59
Author: Vito Lin <vi...@gmail.com>
AuthorDate: Tue Oct 20 16:34:51 2026 +0800

    [SPARK-60173][PYTHON][TEST] Replace type: ignore[union-attr] in pyspark.ml
    
    ### What changes were proposed in this pull request?
    
    Remove five `type: ignore[union-attr]` comments in `pyspark.ml` by narrowing types or correcting annotations:
    
    - `ml/torch/torch_run_process_wrapper.py`: `task.stdin` / `task.stdout` are created with `subprocess.PIPE` and are never `None`; narrow with an `assert`.
    - `ml/connect/io_utils.py`: narrow `sparkContext._gateway` with an `assert`.
    - `ml/wrapper.py`: check `_gateway is not None` before calling `detach`, instead of relying on the surrounding `except`.
    - `ml/connect/tuning.py`: `param_map` comes from `Sequence[ParamMap]`, so annotate it as `ParamMap` instead of `Any`.
    - `ml/connect/base.py`: `Estimator.fit` only accepts a single `ParamMap` and never returns a list, but its return type was declared as `Union[M, List[M]]`. Correct it to `M`. This was the root cause of the ignore in `tuning.py`.
    
    ### Why are the changes needed?
    
    `type: ignore` hides real type errors. These five were covering either an un-narrowed `Optional` or an incorrect annotation. Replacing them lets mypy check the code, and fixes a misleading return type on `Estimator.fit`.
    
    ### Does this PR introduce _any_ user-facing change?
    
    No.
    
    ### How was this patch tested?
    
    `dev/lint-python --mypy` passes.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Co-authored by Claude. Author reviewed every line, ran the tests, and verified the coverage results locally.
    
    Closes #59377 from vito-lin-dev/SPARK-60173.
    
    Authored-by: Vito Lin <vi...@gmail.com>
    Signed-off-by: Ruifeng Zheng <ru...@apache.org>
---
 python/pyspark/ml/connect/base.py                    | 2 +-
 python/pyspark/ml/connect/io_utils.py                | 3 ++-
 python/pyspark/ml/connect/tuning.py                  | 6 ++----
 python/pyspark/ml/torch/torch_run_process_wrapper.py | 5 +++--
 python/pyspark/ml/wrapper.py                         | 7 +++----
 5 files changed, 11 insertions(+), 12 deletions(-)

diff --git a/python/pyspark/ml/connect/base.py b/python/pyspark/ml/connect/base.py
index 3497aa9c87fa..b2307dce1cf0 100644
--- a/python/pyspark/ml/connect/base.py
+++ b/python/pyspark/ml/connect/base.py
@@ -78,7 +78,7 @@ class Estimator(Params, Generic[M], metaclass=ABCMeta):
         self,
         dataset: Union[DataFrame, pd.DataFrame],
         params: Optional["ParamMap"] = None,
-    ) -> Union[M, List[M]]:
+    ) -> M:
         """
         Fits a model to the input dataset with optional parameters.
 
diff --git a/python/pyspark/ml/connect/io_utils.py b/python/pyspark/ml/connect/io_utils.py
index c6104d12d094..212b020ef95e 100644
--- a/python/pyspark/ml/connect/io_utils.py
+++ b/python/pyspark/ml/connect/io_utils.py
@@ -36,7 +36,8 @@ def _copy_file_from_local_to_fs(local_path: str, dest_path: str) -> None:
     if is_remote():
         session.copyFromLocalToFs(local_path, dest_path)
     else:
-        jvm = session.sparkContext._gateway.jvm  # type: ignore[union-attr]
+        assert session.sparkContext._gateway is not None
+        jvm = session.sparkContext._gateway.jvm
         getattr(jvm, "org.apache.spark.ml.python.MLUtil").copyFileFromLocalToFs(
             local_path, dest_path
         )
diff --git a/python/pyspark/ml/connect/tuning.py b/python/pyspark/ml/connect/tuning.py
index d31e0fdad1df..d6b1b6117508 100644
--- a/python/pyspark/ml/connect/tuning.py
+++ b/python/pyspark/ml/connect/tuning.py
@@ -173,7 +173,7 @@ def _parallelFitTasks(
             "An active SparkSession is required for running cross validator fit tasks."
         )
 
-    def get_single_task(index: int, param_map: Any) -> Callable[[], Tuple[int, float]]:
+    def get_single_task(index: int, param_map: "ParamMap") -> Callable[[], Tuple[int, float]]:
         def single_task() -> Tuple[int, float]:
             if not is_remote():
                 # Active session is thread-local variable, in background thread the active session
@@ -183,9 +183,7 @@ def _parallelFitTasks(
                 )
 
             model = estimator.fit(train, param_map)
-            metric = evaluator.evaluate(
-                model.transform(validation, param_map)  # type: ignore[union-attr]
-            )
+            metric = evaluator.evaluate(model.transform(validation, param_map))
             return index, metric
 
         return single_task
diff --git a/python/pyspark/ml/torch/torch_run_process_wrapper.py b/python/pyspark/ml/torch/torch_run_process_wrapper.py
index 88415a2c8349..7493edb9d0fa 100644
--- a/python/pyspark/ml/torch/torch_run_process_wrapper.py
+++ b/python/pyspark/ml/torch/torch_run_process_wrapper.py
@@ -66,9 +66,10 @@ if __name__ == "__main__":
     signal.signal(signal.SIGTERM, sigterm_handler)
 
     t.start()
-    task.stdin.close()  # type: ignore[union-attr]
+    assert task.stdin is not None and task.stdout is not None
+    task.stdin.close()
     try:
-        for line in task.stdout:  # type: ignore[union-attr]
+        for line in task.stdout:
             decoded = line.decode("utf-8")
             print(decoded.rstrip())
         task.wait()
diff --git a/python/pyspark/ml/wrapper.py b/python/pyspark/ml/wrapper.py
index 09563c3c32da..5f3a118232b9 100644
--- a/python/pyspark/ml/wrapper.py
+++ b/python/pyspark/ml/wrapper.py
@@ -66,10 +66,9 @@ class JavaWrapper:
         try:
             from pyspark.core.context import SparkContext
 
-            if SparkContext._active_spark_context and self._java_obj is not None:
-                SparkContext._active_spark_context._gateway.detach(  # type: ignore[union-attr]
-                    self._java_obj
-                )
+            sc = SparkContext._active_spark_context
+            if sc is not None and sc._gateway is not None and self._java_obj is not None:
+                sc._gateway.detach(self._java_obj)
         except Exception:
             pass
 


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org