Skip to content

Commit aa54031

Browse files
authored
Allow accessing a TaskGroup's members via [] (#64430)
1 parent b529f12 commit aa54031

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

‎task-sdk/src/airflow/sdk/definitions/taskgroup.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,10 @@ def _validate_dag(self, _attr, dag):
141141
if not dag:
142142
raise RuntimeError("TaskGroup can only be used inside a dag")
143143

144+
def __getitem__(self, key: str) -> DAGNode:
145+
"""Return a child node by label via ``tg[label]`` syntax. See `get_child_by_label`."""
146+
return self.get_child_by_label(key)
147+
144148
def __attrs_post_init__(self):
145149
# TODO: If attrs supported init only args we could use that here
146150
# https://github.com/python-attrs/attrs/issues/342

‎task-sdk/tests/task_sdk/definitions/test_taskgroup.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,31 @@ def test_build_task_group_with_prefix():
223223
assert group4.get_child_by_label("task4") == task4
224224

225225

226+
@pytest.mark.parametrize(
227+
"prefix",
228+
[
229+
pytest.param(True, id="prefix_on"),
230+
pytest.param(False, id="prefix_off"),
231+
],
232+
)
233+
def test_taskgroup_getitem_returns_child_by_label(prefix: bool):
234+
"""Tests that TaskGroup[label] returns the correct child task or subgroup."""
235+
logical_date = pendulum.datetime(2020, 1, 1)
236+
with DAG("test_getitem", start_date=logical_date):
237+
with TaskGroup("group1", prefix_group_id=prefix) as group1:
238+
task1 = EmptyOperator(task_id="task1")
239+
with TaskGroup("subgroup", prefix_group_id=prefix) as subgroup:
240+
task2 = EmptyOperator(task_id="task2")
241+
242+
assert group1["task1"] == task1
243+
assert group1["subgroup"] == subgroup
244+
assert group1["subgroup"]["task2"] == task2
245+
246+
# Missing label raises KeyError
247+
with pytest.raises(KeyError):
248+
group1["nonexistent"]
249+
250+
226251
def test_build_task_group_with_prefix_functionality():
227252
"""
228253
Tests TaskGroup prefix_group_id functionality - additional test for comprehensive coverage.

0 commit comments

Comments
 (0)