Type checkers¶
schedr types its API so that mypy (--strict), pyright and basedpyright check a DAG body as
you write it: a wrong argument is reported in your editor, before the file is loaded. They
check less than schedr does when it loads the file (below), so a clean editor is no proof
that the file loads.
"""How type checkers read a DAG body: calls as their values, outcomes from `Data`."""
from datetime import datetime
from schedr import (
Chosen,
CommandOperator,
Dag,
Data,
Done,
Outcome,
RunIf,
Task,
branch,
dag_ctx,
task,
)
class Found(Data, frozen=True):
"""Rows were found."""
rows: list[str]
class Empty(Data, frozen=True):
"""Nothing to load."""
reason: str
class Disk(Outcome):
"""What `df` found: each member is the exit code that means it."""
ROOM = 0
FULL = 1
with Dag(
"typed_flow",
description="A flow written so that type checkers read each task's output type.",
trigger=None,
):
@task
def find(day: datetime) -> Found | Empty:
return Found([f"{day:%Y-%m-%d}.csv"])
@task
def load(found: Found) -> int:
return len(found.rows)
@task
def count_files(rows: list[str]) -> int:
return len(rows)
@task(run_if=RunIf.ALL_SUCCEEDED) # skipped with `load`, so never given None
def report(loaded: int, files: int) -> None:
print(f"loaded {loaded} of {files}")
@task
def note(state: Disk) -> None:
print(state.name)
@task
def archive() -> None:
print("archived")
found = find(dag_ctx.run.planned_for) # a `datetime` for type checkers
rows = found.on(Found) # `Found`: `.on` comes from `Data`
loaded = load(rows) # `int`
files = count_files(rows.rows) # `rows.rows` is `list[str]`
done: Done = report(loaded, files) # a task returning None: `Done`
disk = CommandOperator("disk", "exit 0", outcomes=Disk) # `CommandOperator[Disk]`
note(disk.outcome) # `Disk`
stored = archive()
@branch
def keep() -> list[Task]:
return [stored]
chosen: Chosen = keep()
done >> chosen >> stored # `>>` orders Done and Chosen
disk.on(Disk.ROOM) >> stored
How a DAG body reads¶
Inside with Dag(...), calling a task records it and gives a reference to its output.
Type checkers read that call as the value it stands for: find(...) above is a
Found | Empty, load(rows) an int. So the value passes to a task taking that type, and
its fields are typed (rows.rows is a list[str]). Passing the wrong type is reported, as
it would be for an ordinary call.
What you write |
How type checkers read it |
|---|---|
A call of a task returning |
|
A call of a task returning |
|
A wait step returning |
|
A call of a |
|
|
|
A call of a task returning an |
The enum; |
|
|
|
Itself; |
|
|
|
|
|
|
|
|
>> works where one side is a task call returning None, a branch call, an operator, an
outcome class or enum, or a command’s output. Between two values of builtin types
(rows >> counts, a list and an int), it type-checks on neither side: write
chain(rows, counts).
For wait-step values without >>, such as str, use chain to order after a narrowed
value. See Wait steps for routing after a value or timeout.
For an async task in a test, use await task.fn(...): it is typed as a coroutine and
retains the task’s declarations. await task() runs outside a DAG but type checkers flag it,
because the call reads as the task’s value in a DAG. For -> None, awaiting .fn gives
None. Without an async test plugin, use asyncio.run(task.fn(...)).
Outcome classes¶
An outcome class (a member of a union a task returns) derives from schedr.Data,
which makes it a dataclass and gives it .on and >> for type checkers:
class Found(Data, frozen=True): # instead of @dataclass(frozen=True)
rows: list[str]
The dataclass options are class keywords: frozen, eq, order, kw_only,
unsafe_hash, repr (not slots). Ordinary data, a class a task returns on its own or
inside a list, stays a plain @dataclass. A Pydantic outcome model derives from
schedr.pydantic.Model instead of BaseModel (see
Data flow).
A plain @dataclass still works as an outcome class: the DAG runs as written. Type
checkers then reject .on(Plain), because the class doesn’t declare it. Write
on(output, Plain) instead, which runs the same and is typed Plain:
from schedr import on
plain_load(on(plain_fetch(), Plain))
Loading such a file raises a schedr.TypingHint warning naming the class. schedr dags check prints it as a warn line, and pytest lists it in its warnings summary. The check
still passes.
What only loading the file checks¶
Type checkers check the types of what you pass. Loading the file checks the DAG itself, and finds what they can’t:
Using an output as a value in the DAG body. Type checkers read
rowsas a list, so they acceptif rows:,len(rows),for r in rows:orrows[0].name.upper(). When the file is loaded,rowsis a reference that exists only at run time, and each of these fails:if,==,!=andstr()with “an output can’t be used as a value in the DAG file” (the same for.outcome), andforwith that message for an output.dag_ctxfields failif,==,!=andstr()with “a reference can’t be used as a value in the DAG file”, anddag_ctx.paramsfailsforwith it too. The others fail with Python’s ownTypeError. In a DAG body, pass outputs, take their fields (rows[0].name), and order tasks; decide in a task.A t-string inside a list or dict is a
strin its place:[t"{n}"]for alist[int]parameter is refused when the file loads, as a t-string passed whole is.An output or task of another DAG. Type checkers accept
consume(first_out)in a second DAG; when the file loads it is refused (“taskxbelongs to DAGa, notb”), even if this DAG has a task of the same ID. Call the task again in this DAG.Nonefrom a skipped edge. UnderNONE_FAILED, an argument isNonewhen its edge isn’t taken and the task runs through another edge. That is an.on(...)that leaves an outcome out, or an upstream task that may be skipped. An.on(...)that names every outcome of the task is an edge always taken, so it gives noNone. The parameter must allowNone, or the task takesrun_if=RunIf.ALL_SUCCEEDED(asreportabove). Type checkers don’t know which edges may be skipped.Outcomes and graphs:
.on(...)with a class that isn’t one of the task’s outcomes, cycles and duplicate task IDs. A branch returning a task that is not directly downstream is checked when the branch runs, rather than when the file loads.
Settings¶
mypy needs nothing beyond --strict. For basedpyright, DAG code makes
statements of expressions on purpose: a >> b records a dependency, and
CommandOperator(...) alone on a line records a task. Turn off the two rules that report
them, in pyproject.toml:
[tool.basedpyright]
reportUnusedExpression = false
reportUnusedCallResult = false
For pyright, put the same options under [tool.pyright].
schedr’s own make lint checks the example DAGs this way, with mypy --strict and
basedpyright, so these pages stay type-clean.