Skip to content

Commit 9559bb0

Browse files
authored
fix: preserve definition locals for postponed task annotations (#1026)
1 parent 4b96291 commit 9559bb0

13 files changed

Lines changed: 581 additions & 89 deletions

File tree

‎.github/workflows/main.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ on:
1111
- main
1212
pull_request:
1313
branches:
14-
- '*'
14+
- '**'
1515
merge_group:
1616

1717
permissions: {}

‎.github/workflows/zizmor.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ on:
66
- main
77
pull_request:
88
branches:
9-
- '*'
9+
- '**'
1010
schedule:
1111
- cron: '0 7 * * 1'
1212
workflow_dispatch:

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ releases are available on [PyPI](https://pypi.org/project/pytask) and
77

88
## Unreleased
99

10+
- [#1026](https://github.com/pytask-dev/pytask/pull/1026) preserves definition-local
11+
bindings for generated tasks with postponed annotations and releases temporary
12+
snapshots after collection or generator failures. Internal task registration no
13+
longer shadows annotation globals with pytask's own locals.
1014
- [#1025](https://github.com/pytask-dev/pytask/pull/1025) fixes postponed annotation
1115
evaluation across Python versions and avoids eager evaluation during task signature
1216
inspection. Parameter defaults no longer override module globals or builtins when

‎docs/source/how_to_guides/using_task_returns.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,13 @@ It works because internally the path is converted to a
2525
[`pytask.PathNode`](../reference_guides/api/nodes_and_tasks.md#pytask.PathNode) that is
2626
able to store objects of type `str` and `bytes`.
2727

28+
When `@pytask.task` decorates a function inside another function, such as a task
29+
generator, pytask takes a shallow snapshot of the enclosing function's local bindings to
30+
evaluate annotations during collection. This also works with
31+
`from __future__ import annotations`, so each generated task can refer to its own loop
32+
values. The referenced objects are shared, and the snapshot is released after task
33+
collection. Module-level future annotations continue to use current module globals.
34+
2835
!!! note
2936

3037
Read the explanation on [nodes](../how_to_guides/writing_custom_nodes.md) to learn more

‎src/_pytask/collect.py‎

Lines changed: 40 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -70,44 +70,54 @@ def pytask_collect(session: Session) -> bool:
7070
"""Collect tasks."""
7171
session.collection_start = time.time()
7272

73-
_collect_from_paths(session)
74-
_collect_from_tasks(session)
75-
_collect_not_collected_tasks(session)
76-
77-
session.tasks.extend(
78-
i.node
79-
for i in session.collection_reports
80-
if i.outcome == CollectionOutcome.SUCCESS and isinstance(i.node, PTask)
81-
)
82-
8373
try:
84-
session.hook.pytask_collect_modify_tasks(session=session, tasks=session.tasks)
85-
validate_unique_task_signatures(session.tasks)
86-
except Exception: # noqa: BLE001 # pragma: no cover
87-
report = CollectionReport.from_exception(
88-
outcome=CollectionOutcome.FAIL, exc_info=sys.exc_info()
74+
_collect_from_paths(session)
75+
_collect_from_tasks(session)
76+
_collect_not_collected_tasks(session)
77+
78+
session.tasks.extend(
79+
i.node
80+
for i in session.collection_reports
81+
if i.outcome == CollectionOutcome.SUCCESS and isinstance(i.node, PTask)
8982
)
90-
session.collection_reports.append(report)
9183

92-
session.hook.pytask_collect_log(
93-
session=session, reports=session.collection_reports, tasks=session.tasks
94-
)
84+
try:
85+
session.hook.pytask_collect_modify_tasks(
86+
session=session, tasks=session.tasks
87+
)
88+
validate_unique_task_signatures(session.tasks)
89+
except Exception: # noqa: BLE001 # pragma: no cover
90+
report = CollectionReport.from_exception(
91+
outcome=CollectionOutcome.FAIL, exc_info=sys.exc_info()
92+
)
93+
session.collection_reports.append(report)
9594

96-
_clear_annotation_locals(session.tasks)
95+
session.hook.pytask_collect_log(
96+
session=session, reports=session.collection_reports, tasks=session.tasks
97+
)
9798

98-
return True
99+
return True
100+
finally:
101+
_clear_annotation_locals(session.tasks)
102+
_clear_annotation_locals(
103+
report.node
104+
for report in session.collection_reports
105+
if isinstance(report.node, PTask)
106+
)
99107

100108

101-
def _clear_annotation_locals(tasks: list[PTask]) -> None:
109+
def _clear_annotation_locals(tasks: Iterable[PTask | TaskFunction]) -> None:
102110
"""Drop decoration-time locals snapshots once collection finishes.
103111
104112
The snapshot is only needed to evaluate deferred annotations while collecting
105-
dependencies/products. Keeping it afterwards can retain non-picklable objects (for
106-
example locks) and break parallel backends that cloudpickle task functions.
113+
dependencies/products and running collection hooks. Keeping it afterwards can
114+
retain non-picklable objects (for example locks) and break parallel backends that
115+
cloudpickle task functions.
107116
"""
108117
for task in tasks:
109-
if isinstance(task.function, TaskFunction):
110-
task.function.pytask_meta.annotation_locals = None
118+
function = task.function if isinstance(task, PTask) else task
119+
if isinstance(function, TaskFunction):
120+
function.pytask_meta.annotation_locals = None
111121

112122

113123
def _collect_from_paths(session: Session) -> None:
@@ -135,7 +145,11 @@ def _collect_from_tasks(session: Session) -> None:
135145
if is_task_function(raw_task):
136146
if not isinstance(raw_task, TaskFunction):
137147
raw_task = task_decorator()(raw_task) # noqa: PLW2901
148+
# This registration frame is not the callable's definition scope.
149+
raw_task.pytask_meta.annotation_locals = None
138150

151+
# Keep `path` in sync with the collision fixture in
152+
# test_programmatic_annotation_globals_do_not_capture_collection_locals.
139153
path = get_file(raw_task)
140154
name = raw_task.pytask_meta.name
141155

‎src/_pytask/models.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,9 @@ class CollectionMetadata:
4242
A dictionary containing keyword arguments which are passed to the task when it
4343
is executed.
4444
annotation_locals
45-
A snapshot of local variables captured during decoration which helps evaluate
46-
deferred annotations later on.
45+
A shallow snapshot of definition-local bindings captured during decoration
46+
which helps evaluate deferred annotations later on. Values are shared, and
47+
the snapshot is released after task collection.
4748
markers
4849
A list of markers that are attached to the task.
4950
name

‎src/_pytask/provisional.py‎

Lines changed: 61 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from typing import TYPE_CHECKING
66
from typing import Any
77

8+
from _pytask.collect import _clear_annotation_locals
89
from _pytask.config import hookimpl
910
from _pytask.dag import create_dag_from_session
1011
from _pytask.exceptions import CollectionError
@@ -30,6 +31,7 @@
3031
from _pytask.reports import CollectionReport
3132
from _pytask.reports import ExecutionReport
3233
from _pytask.session import Session
34+
from _pytask.typing import TaskFunction
3335

3436

3537
@hookimpl(tryfirst=True)
@@ -53,49 +55,67 @@ def pytask_execute_task(session: Session, task: PTask) -> bool | None:
5355
if not is_task_generator(task):
5456
return None
5557

56-
execute_task(task)
58+
registered_functions = {
59+
id(function) for functions in COLLECTED_TASKS.values() for function in functions
60+
}
61+
try:
62+
execute_task(task)
63+
except BaseException:
64+
# Children can be registered before the generator raises, without reaching
65+
# collection below. Release only their snapshots and preserve the exception.
66+
_clear_annotation_locals(
67+
function
68+
for functions in COLLECTED_TASKS.values()
69+
for function in functions
70+
if id(function) not in registered_functions
71+
)
72+
raise
5773

58-
name_to_function: Mapping[str, Callable[..., Any] | PTask]
59-
if isinstance(task, PTaskWithPath) and task.path in COLLECTED_TASKS:
60-
tasks = COLLECTED_TASKS.pop(task.path)
61-
name_to_function = parse_collected_tasks_with_task_marker(tasks)
62-
elif None in COLLECTED_TASKS:
63-
tasks = COLLECTED_TASKS.pop(None)
74+
tasks: list[TaskFunction] = []
75+
try:
76+
if isinstance(task, PTaskWithPath) and task.path in COLLECTED_TASKS:
77+
tasks = COLLECTED_TASKS.pop(task.path)
78+
elif None in COLLECTED_TASKS:
79+
tasks = COLLECTED_TASKS.pop(None)
80+
else:
81+
msg = f"The task generator {task.name!r} did not create any tasks."
82+
raise RuntimeError(msg)
83+
84+
name_to_function: Mapping[str, Callable[..., Any] | PTask]
6485
name_to_function = parse_collected_tasks_with_task_marker(tasks)
65-
else:
66-
msg = f"The task generator {task.name!r} did not create any tasks."
67-
raise RuntimeError(msg)
68-
69-
new_reports: list[CollectionReport] = []
70-
for name, function in name_to_function.items():
71-
report = session.hook.pytask_collect_task_protocol(
72-
session=session,
73-
reports=new_reports,
74-
path=task.path if isinstance(task, PTaskWithPath) else None,
75-
name=name,
76-
obj=function,
77-
)
78-
if report is not None:
79-
new_reports.append(report)
80-
81-
session.collection_reports.extend(new_reports)
82-
failed_reports = [
83-
report for report in new_reports if report.outcome == CollectionOutcome.FAIL
84-
]
85-
if failed_reports:
86-
_raise_error_for_failed_generated_tasks(task, failed_reports)
87-
88-
generated_tasks = [
89-
report.node
90-
for report in new_reports
91-
if report.outcome == CollectionOutcome.SUCCESS
92-
and isinstance(report.node, PTask)
93-
]
94-
_commit_generated_tasks(session, generated_tasks)
95-
# Generators must run to discover tasks even in simulation modes.
96-
if session.config["dry_run"] or session.config["explain"]:
97-
raise WouldBeExecuted
98-
return True
86+
87+
new_reports: list[CollectionReport] = []
88+
for name, function in name_to_function.items():
89+
report = session.hook.pytask_collect_task_protocol(
90+
session=session,
91+
reports=new_reports,
92+
path=task.path if isinstance(task, PTaskWithPath) else None,
93+
name=name,
94+
obj=function,
95+
)
96+
if report is not None:
97+
new_reports.append(report)
98+
99+
session.collection_reports.extend(new_reports)
100+
failed_reports = [
101+
report for report in new_reports if report.outcome == CollectionOutcome.FAIL
102+
]
103+
if failed_reports:
104+
_raise_error_for_failed_generated_tasks(task, failed_reports)
105+
106+
generated_tasks = [
107+
report.node
108+
for report in new_reports
109+
if report.outcome == CollectionOutcome.SUCCESS
110+
and isinstance(report.node, PTask)
111+
]
112+
_commit_generated_tasks(session, generated_tasks)
113+
# Generators must run to discover tasks even in simulation modes.
114+
if session.config["dry_run"] or session.config["explain"]:
115+
raise WouldBeExecuted
116+
return True
117+
finally:
118+
_clear_annotation_locals(tasks)
99119

100120

101121
def _raise_error_for_failed_generated_tasks(

‎src/_pytask/task_utils.py‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -233,14 +233,18 @@ def create_text_file() -> Annotated[str, Path("file.txt")]:
233233
```
234234
235235
"""
236-
# Capture the caller's frame locals for deferred annotation evaluation in Python
237-
# 3.14+. If ``from __future__ import annotations`` is active, keep the pre-3.14
238-
# behavior by evaluating annotations against current globals instead of snapshots.
236+
# Snapshot definition-local bindings, including stringified annotations. Like
237+
# Pydantic, keep future annotations at module scope tied to current globals.
238+
# Retain snapshots for native lazy annotations in module-level task loops.
239239
caller_frame = sys._getframe(1)
240240
has_future_annotations = bool(
241241
caller_frame.f_code.co_flags & __future__.annotations.compiler_flag
242242
)
243-
caller_locals = None if has_future_annotations else caller_frame.f_locals.copy()
243+
caller_locals = (
244+
None
245+
if has_future_annotations and caller_frame.f_code.co_name == "<module>"
246+
else caller_frame.f_locals.copy()
247+
)
244248

245249
def wrapper(func: Callable[P, R_co]) -> TaskDecorated[P, R_co]:
246250
# Omits frame when a builtin function is wrapped.
@@ -354,6 +358,8 @@ def _parse_after(
354358
for func in after:
355359
if not isinstance(func, TaskFunction):
356360
func = task()(func) # noqa: PLW2901
361+
# This registration frame is not the callable's definition scope.
362+
func.pytask_meta.annotation_locals = None
357363
new_after.append(func.pytask_meta._id)
358364
return new_after
359365
msg = (

‎tests/conftest.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,8 @@ def pytest_collection_modifyitems(session, config, items) -> None: # noqa: ARG0
158158
return
159159
for item in items:
160160
if isinstance(item, NotebookItem):
161+
if item.path.name == "test_task_generator.ipynb":
162+
continue
161163
item.add_marker(pytest.mark.xfail(reason="The tests are flaky."))
162164

163165

0 commit comments

Comments
 (0)