You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by js...@apache.org on 2026/05/02 09:54:40 UTC

(airflow) branch main updated: Use contextlib.suppress instead of try-except-pass and re-enable SIM105 (#66193)

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

jscheffl pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git


The following commit(s) were added to refs/heads/main by this push:
     new 251fe925b54 Use contextlib.suppress instead of try-except-pass and re-enable SIM105 (#66193)
251fe925b54 is described below

commit 251fe925b5484fe6ff11e6b6de46ef8099c320c9
Author: Colten <70...@users.noreply.github.com>
AuthorDate: Sat May 2 17:54:33 2026 +0800

    Use contextlib.suppress instead of try-except-pass and re-enable SIM105 (#66193)
    
    Signed-off-by: ColtenOuO <ju...@gmail.com>
---
 airflow-core/src/airflow/cli/hot_reload.py                       | 5 ++---
 airflow-core/tests/unit/api_fastapi/core_api/test_app.py         | 5 ++---
 airflow-core/tests/unit/jobs/test_triggerer_job.py               | 6 +++---
 airflow-core/tests/unit/utils/test_process_utils.py              | 4 +---
 dev/breeze/src/airflow_breeze/utils/airflow_release_validator.py | 9 +++------
 dev/breeze/src/airflow_breeze/utils/reproducible.py              | 6 ++----
 dev/ide_setup/setup_idea.py                                      | 9 +++------
 providers/mongo/tests/conftest.py                                | 5 ++---
 pyproject.toml                                                   | 2 +-
 task-sdk/src/airflow/sdk/execution_time/context.py               | 4 +---
 10 files changed, 20 insertions(+), 35 deletions(-)

diff --git a/airflow-core/src/airflow/cli/hot_reload.py b/airflow-core/src/airflow/cli/hot_reload.py
index ecf64c2781d..56fb97efcb9 100644
--- a/airflow-core/src/airflow/cli/hot_reload.py
+++ b/airflow-core/src/airflow/cli/hot_reload.py
@@ -19,6 +19,7 @@
 
 from __future__ import annotations
 
+import contextlib
 import os
 import signal
 import sys
@@ -94,10 +95,8 @@ def _terminate_process_tree(
 
         # Terminate all children first
         for child in children:
-            try:
+            with contextlib.suppress(psutil.NoSuchProcess, psutil.AccessDenied):
                 child.terminate()
-            except (psutil.NoSuchProcess, psutil.AccessDenied):
-                pass
 
         # Terminate the parent
         parent.terminate()
diff --git a/airflow-core/tests/unit/api_fastapi/core_api/test_app.py b/airflow-core/tests/unit/api_fastapi/core_api/test_app.py
index a30c803f50c..4aadcdd005a 100644
--- a/airflow-core/tests/unit/api_fastapi/core_api/test_app.py
+++ b/airflow-core/tests/unit/api_fastapi/core_api/test_app.py
@@ -16,6 +16,7 @@
 # under the License.
 from __future__ import annotations
 
+import contextlib
 import inspect
 import typing
 
@@ -70,10 +71,8 @@ class TestStreamingEndpointSessionScope:
                 continue
             returns_streaming = hints.get("return") is StreamingResponse
             if not returns_streaming:
-                try:
+                with contextlib.suppress(OSError, TypeError):
                     returns_streaming = "StreamingResponse" in inspect.getsource(route.endpoint)
-                except (OSError, TypeError):
-                    pass
             if not returns_streaming:
                 continue
             fqn = f"{route.endpoint.__module__}.{route.endpoint.__qualname__}"
diff --git a/airflow-core/tests/unit/jobs/test_triggerer_job.py b/airflow-core/tests/unit/jobs/test_triggerer_job.py
index da060d62944..8d0fde20b75 100644
--- a/airflow-core/tests/unit/jobs/test_triggerer_job.py
+++ b/airflow-core/tests/unit/jobs/test_triggerer_job.py
@@ -18,6 +18,7 @@
 from __future__ import annotations
 
 import asyncio
+import contextlib
 import datetime
 import itertools
 import os
@@ -1671,10 +1672,9 @@ class TestTriggererJobRunner:
         # We don't need to run the full _execute, just verify stats.initialize is called
         # before TriggerRunnerSupervisor.start
         with patch.object(job_runner, "register_signals"):
-            try:
+            # We expect this to fail since we're mocking
+            with contextlib.suppress(Exception):
                 job_runner._execute()
-            except Exception:
-                pass  # We expect this to fail since we're mocking
 
         # Verify stats.initialize was called with the expected configuration parameters
         stats_init_mock.assert_called_once()
diff --git a/airflow-core/tests/unit/utils/test_process_utils.py b/airflow-core/tests/unit/utils/test_process_utils.py
index 5d054db7786..5ebc599b6b6 100644
--- a/airflow-core/tests/unit/utils/test_process_utils.py
+++ b/airflow-core/tests/unit/utils/test_process_utils.py
@@ -80,10 +80,8 @@ time.sleep(300)
             assert not psutil.pid_exists(parent_pid)
             assert not psutil.pid_exists(child_pid)
         finally:
-            try:
+            with suppress(OSError):
                 os.kill(parent.pid, signal.SIGKILL)
-            except OSError:
-                pass
             parent.stdout.close()
             parent.wait()
 
diff --git a/dev/breeze/src/airflow_breeze/utils/airflow_release_validator.py b/dev/breeze/src/airflow_breeze/utils/airflow_release_validator.py
index cbd46cc48f0..889e02eeb51 100644
--- a/dev/breeze/src/airflow_breeze/utils/airflow_release_validator.py
+++ b/dev/breeze/src/airflow_breeze/utils/airflow_release_validator.py
@@ -16,6 +16,7 @@
 # under the License.
 from __future__ import annotations
 
+import contextlib
 import filecmp
 import shutil
 import tarfile
@@ -468,15 +469,11 @@ class AirflowReleaseValidator(ReleaseValidator):
 
         for line in result.stdout.split("\n"):
             if "Unapproved:" in line:
-                try:
+                with contextlib.suppress(IndexError, ValueError):
                     unapproved = int(line.split("Unapproved:")[1].split()[0])
-                except (IndexError, ValueError):
-                    pass
             if "Unknown:" in line:
-                try:
+                with contextlib.suppress(IndexError, ValueError):
                     unknown = int(line.split("Unknown:")[1].split()[0])
-                except (IndexError, ValueError):
-                    pass
 
         details = []
         if error_lines:
diff --git a/dev/breeze/src/airflow_breeze/utils/reproducible.py b/dev/breeze/src/airflow_breeze/utils/reproducible.py
index 218598dd660..b3554abd514 100644
--- a/dev/breeze/src/airflow_breeze/utils/reproducible.py
+++ b/dev/breeze/src/airflow_breeze/utils/reproducible.py
@@ -134,11 +134,9 @@ def repack_deterministically(
                             entry_path.chmod(new_mode)
                         else:
                             # for symlinks on the other hand set rwx for all - to match Linux on MacOS
-                            try:
+                            # (on platforms like Linux symlink permissions cannot be changed)
+                            with contextlib.suppress(NotImplementedError):
                                 entry_path.chmod(0o777, follow_symlinks=False)
-                            except NotImplementedError:
-                                # on platforms like Linux symlink permissions cannot be changed
-                                pass
                         arcname = entry
                         if prepend_path is not None:
                             arcname = os.path.normpath(os.path.join(prepend_path, arcname))
diff --git a/dev/ide_setup/setup_idea.py b/dev/ide_setup/setup_idea.py
index e13959890b1..7cf570d6da3 100755
--- a/dev/ide_setup/setup_idea.py
+++ b/dev/ide_setup/setup_idea.py
@@ -25,6 +25,7 @@
 from __future__ import annotations
 
 import argparse
+import contextlib
 import os
 import platform
 import re
@@ -481,10 +482,8 @@ def _kill_jetbrains_ides(*, confirm: bool = False) -> bool:
         if not should_kill:
             return True
     for pid, _comm in pids:
-        try:
+        with contextlib.suppress(OSError):
             os.kill(pid, signal.SIGTERM)
-        except OSError:
-            pass
     # Wait up to 5 seconds for graceful shutdown.
     for _ in range(10):
         remaining = _find_jetbrains_pids()
@@ -495,10 +494,8 @@ def _kill_jetbrains_ides(*, confirm: bool = False) -> bool:
     # Force-kill any remaining processes.
     remaining = _find_jetbrains_pids()
     for pid, _comm in remaining:
-        try:
+        with contextlib.suppress(OSError):
             os.kill(pid, signal.SIGKILL)
-        except OSError:
-            pass
     print("[green]JetBrains IDE processes force-killed.[/]\n")
     return True
 
diff --git a/providers/mongo/tests/conftest.py b/providers/mongo/tests/conftest.py
index 7f60bd12c8d..22a63f417b3 100644
--- a/providers/mongo/tests/conftest.py
+++ b/providers/mongo/tests/conftest.py
@@ -16,6 +16,7 @@
 # under the License.
 from __future__ import annotations
 
+import contextlib
 import time
 
 import pytest
@@ -40,10 +41,8 @@ def mongodb_container():
             container.start()
         except Exception as exc:
             last_exc = exc
-            try:
+            with contextlib.suppress(Exception):
                 container.stop()
-            except Exception:
-                pass
             if attempt < 2:
                 time.sleep(5 * (attempt + 1))
                 continue
diff --git a/pyproject.toml b/pyproject.toml
index 6eba302bdb6..191e734061e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -662,6 +662,7 @@ extend-select = [
     "RET506", # Unnecessary {branch} after raise statement
     "RET507", # Unnecessary {branch} after continue statement
     "RET508", # Unnecessary {branch} after break statement
+    "SIM105", # Use contextlib.suppress({exception}) instead of try-except-pass
 ]
 ignore = [
     "D100", # Unwanted; Docstring at the top of every file.
@@ -693,7 +694,6 @@ ignore = [
     "COM812",
     "COM819",
     "E501", # Formatted code may exceed the line length, leading to line-too-long (E501) errors.
-    "SIM105", # Use contextlib.suppress({exception}) instead of try-except-pass
 ]
 unfixable = [
     # PT022 replace empty `yield` to empty `return`. Might be fixed with a combination of PLR1711
diff --git a/task-sdk/src/airflow/sdk/execution_time/context.py b/task-sdk/src/airflow/sdk/execution_time/context.py
index 0554e41c2e6..66c1f3aa8b7 100644
--- a/task-sdk/src/airflow/sdk/execution_time/context.py
+++ b/task-sdk/src/airflow/sdk/execution_time/context.py
@@ -649,10 +649,8 @@ class InletEventsAccessor(Sequence["AssetEventResult"]):
         return list(resp.iter_asset_event_results())
 
     def _reset_cache(self) -> None:
-        try:
+        with contextlib.suppress(AttributeError):
             del self._asset_events
-        except AttributeError:
-            pass
 
     def __iter__(self) -> Iterator[AssetEventResult]:
         return iter(self._asset_events)