This is an automated email from the ASF dual-hosted git repository.
shahar1 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 1958e234cce Use Python 3.11 features in place of 3.10-era workarounds
(#77418)
1958e234cce is described below
commit 1958e234cceb2a3ab8256629ef8437d9a546a7df
Author: Shahar Epstein <[email protected]>
AuthorDate: Mon Nov 23 17:54:57 2026 +0200
Use Python 3.11 features in place of 3.10-era workarounds (#77418)
The minimum supported Python is 3.11, so several fallbacks kept for
3.10 are dead code or can use the standard library directly.
Convert enums that already return ``self.value`` from ``__str__`` to
``StrEnum``; ``str()`` and f-string output stay identical. ``StrEnum``
only accepts ``str`` in its constructor, so two call sites that passed
``str | None`` or ``DagRunState | Literal[False]`` are adjusted for mypy.
---
.../api_fastapi/auth/managers/base_auth_manager.py | 12 ++------
.../api_fastapi/execution_api/routes/jobs.py | 2 +-
.../src/airflow/executors/workloads/callback.py | 7 ++---
airflow-core/src/airflow/jobs/job.py | 7 ++---
airflow-core/src/airflow/models/backfill.py | 12 ++------
airflow-core/src/airflow/models/callback.py | 7 ++---
airflow-core/src/airflow/models/connection_test.py | 7 ++---
airflow-core/src/airflow/models/taskinstance.py | 2 +-
airflow-core/src/airflow/task/trigger_rule.py | 7 ++---
airflow-core/src/airflow/task/weight_rule.py | 7 ++---
airflow-core/src/airflow/utils/process_utils.py | 8 +-----
airflow-core/src/airflow/utils/state.py | 32 +++++-----------------
airflow-core/src/airflow/utils/types.py | 5 +---
task-sdk/src/airflow/sdk/api/client.py | 12 --------
task-sdk/src/airflow/sdk/definitions/context.py | 5 +---
.../airflow/sdk/execution_time/callback_runner.py | 4 +--
16 files changed, 31 insertions(+), 105 deletions(-)
diff --git
a/airflow-core/src/airflow/api_fastapi/auth/managers/base_auth_manager.py
b/airflow-core/src/airflow/api_fastapi/auth/managers/base_auth_manager.py
index 7358f1aac03..ce1a8083860 100644
--- a/airflow-core/src/airflow/api_fastapi/auth/managers/base_auth_manager.py
+++ b/airflow-core/src/airflow/api_fastapi/auth/managers/base_auth_manager.py
@@ -23,7 +23,7 @@ import warnings
from abc import ABCMeta, abstractmethod
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
-from enum import Enum
+from enum import StrEnum
from functools import cache, cached_property
from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar
@@ -86,7 +86,7 @@ if TYPE_CHECKING:
else:
# For runtime - provides iteration and validation
- class ResourceMethod(str, Enum):
+ class ResourceMethod(StrEnum):
"""HTTP methods (actions) a user can perform against a resource."""
GET = "GET"
@@ -94,10 +94,7 @@ else:
PUT = "PUT"
DELETE = "DELETE"
- def __str__(self) -> str:
- return self.value
-
- class ExtendedResourceMethod(str, Enum):
+ class ExtendedResourceMethod(StrEnum):
"""Extended HTTP methods including MENU for UI resource
authorization."""
GET = "GET"
@@ -106,9 +103,6 @@ else:
DELETE = "DELETE"
MENU = "MENU"
- def __str__(self) -> str:
- return self.value
-
log = logging.getLogger(__name__)
T = TypeVar("T", bound=BaseUser)
diff --git a/airflow-core/src/airflow/api_fastapi/execution_api/routes/jobs.py
b/airflow-core/src/airflow/api_fastapi/execution_api/routes/jobs.py
index 4e837cecb4c..e4b338d7e1b 100644
--- a/airflow-core/src/airflow/api_fastapi/execution_api/routes/jobs.py
+++ b/airflow-core/src/airflow/api_fastapi/execution_api/routes/jobs.py
@@ -263,7 +263,7 @@ def heartbeat_job(
_check_token_job(job_id, token)
job = session.scalars(select(Job).where(Job.id == job_id)).one()
job.latest_heartbeat = timezone.utcnow()
- return JobHeartbeatResponse(state=JobState(job.state))
+ return JobHeartbeatResponse(state=JobState(str(job.state)))
@router.post(
diff --git a/airflow-core/src/airflow/executors/workloads/callback.py
b/airflow-core/src/airflow/executors/workloads/callback.py
index 16970aa3b29..279bc5ea927 100644
--- a/airflow-core/src/airflow/executors/workloads/callback.py
+++ b/airflow-core/src/airflow/executors/workloads/callback.py
@@ -18,7 +18,7 @@
from __future__ import annotations
-from enum import Enum
+from enum import StrEnum
from pathlib import Path
from typing import TYPE_CHECKING, ClassVar, Literal
from uuid import UUID
@@ -37,7 +37,7 @@ if TYPE_CHECKING:
log = structlog.get_logger(__name__)
-class CallbackFetchMethod(str, Enum):
+class CallbackFetchMethod(StrEnum):
"""Methods used to fetch callback at runtime."""
# For future use once Dag Processor callbacks
(on_success_callback/on_failure_callback) get moved to executors
@@ -46,9 +46,6 @@ class CallbackFetchMethod(str, Enum):
# For deadline callbacks since they import callbacks through the import
path
IMPORT_PATH = "import_path"
- def __str__(self) -> str:
- return self.value
-
# Key in ``CallbackDTO.data`` naming how ``data["kwargs"]`` is encoded.
Without it the kwargs are
# passed to the callback as they are, as for callbacks stored before the key
was introduced.
diff --git a/airflow-core/src/airflow/jobs/job.py
b/airflow-core/src/airflow/jobs/job.py
index 43862eb5a2b..5241bb7aef5 100644
--- a/airflow-core/src/airflow/jobs/job.py
+++ b/airflow-core/src/airflow/jobs/job.py
@@ -19,7 +19,7 @@ from __future__ import annotations
from collections.abc import Callable, Iterable
from datetime import datetime, timedelta
-from enum import Enum
+from enum import StrEnum
from functools import cached_property, lru_cache
from time import sleep
from typing import TYPE_CHECKING, NoReturn
@@ -45,7 +45,7 @@ from airflow.utils.session import NEW_SESSION,
create_session, provide_session
from airflow.utils.sqlalchemy import ExtendedJSON, UtcDateTime
-class JobState(str, Enum):
+class JobState(StrEnum):
"""All possible states that a Job can be in."""
RUNNING = "running"
@@ -53,9 +53,6 @@ class JobState(str, Enum):
RESTARTING = "restarting"
FAILED = "failed"
- def __str__(self) -> str:
- return self.value
-
if TYPE_CHECKING:
from sqlalchemy.orm.session import Session
diff --git a/airflow-core/src/airflow/models/backfill.py
b/airflow-core/src/airflow/models/backfill.py
index 1f64dfa75b9..dcd0ba82754 100644
--- a/airflow-core/src/airflow/models/backfill.py
+++ b/airflow-core/src/airflow/models/backfill.py
@@ -25,7 +25,7 @@ from __future__ import annotations
from collections.abc import Iterable
from datetime import datetime
-from enum import Enum
+from enum import StrEnum
from typing import TYPE_CHECKING, Any
import sqlalchemy as sa
@@ -156,7 +156,7 @@ class UnknownActiveBackfills(AirflowException):
super().__init__(f"Unable to determine the number of active backfills
for DAG {dag_id}")
-class ReprocessBehavior(str, Enum):
+class ReprocessBehavior(StrEnum):
"""
Internal enum for setting reprocess behavior in a backfill.
@@ -167,9 +167,6 @@ class ReprocessBehavior(str, Enum):
COMPLETED = "completed"
NONE = "none"
- def __str__(self) -> str:
- return self.value
-
class Backfill(Base):
"""Model representing a backfill job."""
@@ -245,7 +242,7 @@ class Backfill(Base):
return case(when_condition, else_=None)
-class BackfillDagRunExceptionReason(str, Enum):
+class BackfillDagRunExceptionReason(StrEnum):
"""
Enum for storing reasons why Dag run not created.
@@ -256,9 +253,6 @@ class BackfillDagRunExceptionReason(str, Enum):
ALREADY_EXISTS = "already exists"
UNKNOWN = "unknown"
- def __str__(self) -> str:
- return self.value
-
class BackfillDagRun(Base):
"""Mapping table between backfill run and Dag run."""
diff --git a/airflow-core/src/airflow/models/callback.py
b/airflow-core/src/airflow/models/callback.py
index ee0318dfe02..509a27a35df 100644
--- a/airflow-core/src/airflow/models/callback.py
+++ b/airflow-core/src/airflow/models/callback.py
@@ -19,7 +19,7 @@ from __future__ import annotations
import json
from dataclasses import dataclass
from datetime import datetime
-from enum import Enum
+from enum import StrEnum
from importlib import import_module
from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable
from uuid import UUID
@@ -80,7 +80,7 @@ def _format_kwargs_for_display(kwargs: dict | None) -> Any:
return format_encoded_value_for_display(kwargs) if kwargs else ""
-class CallbackType(str, Enum):
+class CallbackType(StrEnum):
"""
Types of Callbacks.
@@ -91,9 +91,6 @@ class CallbackType(str, Enum):
EXECUTOR = "executor"
DAG_PROCESSOR = "dag_processor"
- def __str__(self) -> str:
- return self.value
-
class CallbackDefinitionProtocol(Protocol):
"""Protocol for TaskSDK Callback definition."""
diff --git a/airflow-core/src/airflow/models/connection_test.py
b/airflow-core/src/airflow/models/connection_test.py
index 16ef4aafffc..38f4d7b569b 100644
--- a/airflow-core/src/airflow/models/connection_test.py
+++ b/airflow-core/src/airflow/models/connection_test.py
@@ -19,7 +19,7 @@ from __future__ import annotations
import secrets
from dataclasses import dataclass
from datetime import datetime
-from enum import Enum
+from enum import StrEnum
from typing import TYPE_CHECKING
from uuid import UUID
@@ -50,7 +50,7 @@ if TYPE_CHECKING:
log = structlog.get_logger(__name__)
-class ConnectionTestState(str, Enum):
+class ConnectionTestState(StrEnum):
"""All possible states of a connection test."""
PENDING = "pending"
@@ -59,9 +59,6 @@ class ConnectionTestState(str, Enum):
SUCCESS = "success"
FAILED = "failed"
- def __str__(self) -> str:
- return self.value
-
ACTIVE_STATES = frozenset(
(ConnectionTestState.PENDING, ConnectionTestState.QUEUED,
ConnectionTestState.RUNNING)
diff --git a/airflow-core/src/airflow/models/taskinstance.py
b/airflow-core/src/airflow/models/taskinstance.py
index 4bc4120e105..b51a9b5a067 100644
--- a/airflow-core/src/airflow/models/taskinstance.py
+++ b/airflow-core/src/airflow/models/taskinstance.py
@@ -620,7 +620,7 @@ def clear_task_instances(
)
).all()
if reset_dag_runs:
- dag_run_state = DagRunState(dag_run_state) # Validate the state
value.
+ dag_run_state = DagRunState(str(dag_run_state)) # Validate the
state value.
for dr in drs:
was_finished = dr.state in State.finished_dr_states
if reset_dag_runs:
diff --git a/airflow-core/src/airflow/task/trigger_rule.py
b/airflow-core/src/airflow/task/trigger_rule.py
index 6a9b7e656c1..fed8c85e9f9 100644
--- a/airflow-core/src/airflow/task/trigger_rule.py
+++ b/airflow-core/src/airflow/task/trigger_rule.py
@@ -17,10 +17,10 @@
# under the License.
from __future__ import annotations
-from enum import Enum
+from enum import StrEnum
-class TriggerRule(str, Enum):
+class TriggerRule(StrEnum):
"""Class with task's trigger rules."""
ALL_SUCCESS = "all_success"
@@ -46,6 +46,3 @@ class TriggerRule(str, Enum):
def all_triggers(cls) -> set[str]:
"""Return all trigger rules."""
return set(cls.__members__.values())
-
- def __str__(self) -> str:
- return self.value
diff --git a/airflow-core/src/airflow/task/weight_rule.py
b/airflow-core/src/airflow/task/weight_rule.py
index e25ddd47077..69e800e2a64 100644
--- a/airflow-core/src/airflow/task/weight_rule.py
+++ b/airflow-core/src/airflow/task/weight_rule.py
@@ -17,12 +17,12 @@
# under the License.
from __future__ import annotations
-from enum import Enum
+from enum import StrEnum
import methodtools
-class WeightRule(str, Enum):
+class WeightRule(StrEnum):
"""Weight rules for task priority calculation."""
DOWNSTREAM = "downstream"
@@ -39,6 +39,3 @@ class WeightRule(str, Enum):
def all_weight_rules(cls) -> set[str]:
"""Return all weight rules."""
return set(cls.__members__.values())
-
- def __str__(self) -> str:
- return self.value
diff --git a/airflow-core/src/airflow/utils/process_utils.py
b/airflow-core/src/airflow/utils/process_utils.py
index cfadcc289a0..b455f881b3b 100644
--- a/airflow-core/src/airflow/utils/process_utils.py
+++ b/airflow-core/src/airflow/utils/process_utils.py
@@ -19,7 +19,6 @@
from __future__ import annotations
-import array
import errno
import logging
import multiprocessing
@@ -34,7 +33,6 @@ from airflow import DeprecatedImportWarning
from airflow.utils.platform import IS_WINDOWS
if not IS_WINDOWS:
- import fcntl
import pty
import termios
import tty
@@ -256,11 +254,7 @@ def execute_interactive(cmd: list[str], **kwargs) -> None:
proc.send_signal(sig)
def _sigwinch(sig, frame):
- # On Py3.11+ we could use termios.tcgetwinsize/tcsetwinsize
instead
- buf = array.array("h", [0, 0, 0, 0])
-
- fcntl.ioctl(pty.STDOUT_FILENO, termios.TIOCGWINSZ, buf, True)
- fcntl.ioctl(secondary_fd, termios.TIOCSWINSZ, buf)
+ termios.tcsetwinsize(secondary_fd,
termios.tcgetwinsize(pty.STDOUT_FILENO))
# Set the initial size too
_sigwinch(signal.SIGWINCH, None)
diff --git a/airflow-core/src/airflow/utils/state.py
b/airflow-core/src/airflow/utils/state.py
index 889430c19d0..4d5b6d36d63 100644
--- a/airflow-core/src/airflow/utils/state.py
+++ b/airflow-core/src/airflow/utils/state.py
@@ -17,10 +17,10 @@
# under the License.
from __future__ import annotations
-from enum import Enum
+from enum import StrEnum
-class CallbackState(str, Enum):
+class CallbackState(StrEnum):
"""All possible states of callbacks."""
SCHEDULED = "scheduled"
@@ -30,11 +30,8 @@ class CallbackState(str, Enum):
SUCCESS = "success"
FAILED = "failed"
- def __str__(self) -> str:
- return self.value
-
-class TerminalTIState(str, Enum):
+class TerminalTIState(StrEnum):
"""States that a Task Instance can be in that indicate it has reached a
terminal state."""
SUCCESS = "success"
@@ -43,11 +40,8 @@ class TerminalTIState(str, Enum):
UPSTREAM_FAILED = "upstream_failed"
REMOVED = "removed"
- def __str__(self) -> str:
- return self.value
-
-class IntermediateTIState(str, Enum):
+class IntermediateTIState(StrEnum):
"""States that a Task Instance can be in that indicate it is not yet in a
terminal or running state."""
SCHEDULED = "scheduled"
@@ -58,11 +52,8 @@ class IntermediateTIState(str, Enum):
DEFERRED = "deferred"
AWAITING_INPUT = "awaiting_input"
- def __str__(self) -> str:
- return self.value
-
-class TaskInstanceState(str, Enum):
+class TaskInstanceState(StrEnum):
"""
All possible states that a Task Instance can be in.
@@ -90,11 +81,8 @@ class TaskInstanceState(str, Enum):
DEFERRED = IntermediateTIState.DEFERRED # Deferrable operator waiting on
a trigger
AWAITING_INPUT = IntermediateTIState.AWAITING_INPUT # Parked waiting for
human input (HITL)
- def __str__(self) -> str:
- return self.value
-
-class DagRunState(str, Enum):
+class DagRunState(StrEnum):
"""
All possible states that a DagRun can be in.
@@ -108,20 +96,14 @@ class DagRunState(str, Enum):
SUCCESS = "success"
FAILED = "failed"
- def __str__(self) -> str:
- return self.value
-
-class DagSchedulingState(str, Enum):
+class DagSchedulingState(StrEnum):
"""States controlling whether a Dag can create and schedule work."""
ACTIVE = "active"
DRAINING = "draining"
PAUSED = "paused"
- def __str__(self) -> str:
- return self.value
-
class State:
"""Static class with task instance state constants and color methods to
avoid hard-coding."""
diff --git a/airflow-core/src/airflow/utils/types.py
b/airflow-core/src/airflow/utils/types.py
index 46fb18339e1..cf867fd3a38 100644
--- a/airflow-core/src/airflow/utils/types.py
+++ b/airflow-core/src/airflow/utils/types.py
@@ -22,7 +22,7 @@ import enum
from airflow.utils.deprecation_tools import add_deprecated_classes
-class DagRunType(str, enum.Enum):
+class DagRunType(enum.StrEnum):
"""Class with DagRun types."""
BACKFILL_JOB = "backfill"
@@ -32,9 +32,6 @@ class DagRunType(str, enum.Enum):
ASSET_TRIGGERED = "asset_triggered"
ASSET_MATERIALIZATION = "asset_materialization"
- def __str__(self) -> str:
- return self.value
-
def generate_run_id(self, *, suffix: str) -> str:
"""
Generate a string for DagRun based on suffix string.
diff --git a/task-sdk/src/airflow/sdk/api/client.py
b/task-sdk/src/airflow/sdk/api/client.py
index 0531b57e582..45572681a2b 100644
--- a/task-sdk/src/airflow/sdk/api/client.py
+++ b/task-sdk/src/airflow/sdk/api/client.py
@@ -204,16 +204,9 @@ def get_json_error(response: httpx2.Response):
def raise_on_4xx_5xx(response: httpx2.Response):
- return get_json_error(response) or response.raise_for_status()
-
-
-# Py 3.11+ version
-def raise_on_4xx_5xx_with_note(response: httpx2.Response):
try:
return get_json_error(response) or response.raise_for_status()
except httpx2.HTTPStatusError as e:
- if TYPE_CHECKING:
- assert hasattr(e, "add_note")
e.add_note(
f"Correlation-id={response.headers.get('correlation-id', None) or
response.request.headers.get('correlation-id', 'no-correlation-id')}"
)
@@ -226,11 +219,6 @@ def raise_on_4xx_5xx_with_note(response: httpx2.Response):
raise
-if hasattr(BaseException, "add_note"):
- # Py 3.11+
- raise_on_4xx_5xx = raise_on_4xx_5xx_with_note
-
-
def add_correlation_id(request: httpx2.Request):
request.headers["correlation-id"] = str(uuid7())
diff --git a/task-sdk/src/airflow/sdk/definitions/context.py
b/task-sdk/src/airflow/sdk/definitions/context.py
index df305bcde0e..df25019d7ea 100644
--- a/task-sdk/src/airflow/sdk/definitions/context.py
+++ b/task-sdk/src/airflow/sdk/definitions/context.py
@@ -24,15 +24,12 @@ from collections.abc import MutableMapping
from typing import TYPE_CHECKING, Any, NamedTuple, NotRequired, TypedDict, cast
-class CallbackSource(str, enum.Enum):
+class CallbackSource(enum.StrEnum):
"""Whether a callback was triggered at the Dag level or the task level."""
DAG = "dag"
TASK = "task"
- def __str__(self) -> str:
- return self.value
-
class CallbackMeta(NamedTuple):
"""
diff --git a/task-sdk/src/airflow/sdk/execution_time/callback_runner.py
b/task-sdk/src/airflow/sdk/execution_time/callback_runner.py
index 83a80bda0ec..00db2108456 100644
--- a/task-sdk/src/airflow/sdk/execution_time/callback_runner.py
+++ b/task-sdk/src/airflow/sdk/execution_time/callback_runner.py
@@ -21,9 +21,7 @@ from __future__ import annotations
import inspect
import logging
from collections.abc import AsyncIterator, Awaitable, Callable
-from typing import TYPE_CHECKING, Any, Generic, Protocol, TypeVar, cast
-
-from typing_extensions import ParamSpec
+from typing import TYPE_CHECKING, Any, Generic, ParamSpec, Protocol, TypeVar,
cast
if TYPE_CHECKING:
from structlog.typing import FilteringBoundLogger as Logger