Replies: 1 comment
-
|
This is a classic variance mismatch. The fix at the type-stub level: from typing import TypeVar, Generic
from prefect.futures import PrefectFuture
F_co = TypeVar("F_co", bound=PrefectFuture, covariant=True)
class TaskRunner(Generic[F_co]):
...Making Workaround while waiting for the fix: from typing import cast
from prefect.task_runners import TaskRunner
@flow(task_runner=cast(TaskRunner, RayTaskRunner()))
def my_flow():
...Or use The root change needed is in |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
This discussion was created from a Slack thread conversation.
Original Thread: https://prefect-community.slack.com/archives/C079VLLH5D3/p1773940607003809
Summary
A typing variance issue occurs when passing a RayTaskRunner to the @flow decorator in Prefect 3.x. Type checkers (e.g., pyright/mypy) raise an error because TaskRunner’s generic parameter F is invariant, and RayTaskRunner is parameterized over a subtype of PrefectFuture (PrefectRayFuture[T]). At runtime everything works; this is a static typing-only mismatch.
Reproduction
Type checker error (example):
Root cause
@flowdecorator parameter is typed astask_runner: Optional[TaskRunner[PrefectFuture[Any]]].RayTaskRunner(in prefect-ray) isTaskRunner[PrefectRayFuture[T]]wherePrefectRayFuture[T]subclassesPrefectFuture[T].prefect/src/prefect/task_runners.py, F is defined invariant:TaskRunner[PrefectRayFuture[Any]]is not a subtype ofTaskRunner[PrefectFuture[Any]].Why covariance is correct
A scan of
TaskRunnershows F is only used in covariant (return) positions: return types ofsubmit()/map()/duplicate(). F is not used in parameter positions. Making F covariant is therefore semantically correct and safe.Proposed change (one line)
In
src/prefect/task_runners.py, update F to be covariant:Impact
@flow(task_runner=RayTaskRunner())and other third-party task runners returning a PrefectFuture subtype.Workarounds for users today
# type: ignore[arg-type]).References
Request
This discussion was automatically created by the Marvin bot to preserve valuable community insights.
Beta Was this translation helpful? Give feedback.
All reactions