diff --git a/CHANGELOG.md b/CHANGELOG.md index 0639ddef..ac29955b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ releases are available on [PyPI](https://pypi.org/project/pytask) and ## Unreleased +- [#1011](https://github.com/pytask-dev/pytask/pull/1011) adds typing regression + tests for tree utilities and documents inference gaps in pytask plugin use cases. - [#1023](https://github.com/pytask-dev/pytask/pull/1023) adds Python 3.15 tests on Linux, macOS, and Windows. - [#1026](https://github.com/pytask-dev/pytask/pull/1026) preserves definition-local diff --git a/pyproject.toml b/pyproject.toml index 21ffda94..4635b88b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -60,6 +60,7 @@ docs = [ docs-live = ["sphinx-autobuild>=2024.10.3"] plugin-list = ["httpx>=0.27.0", "tabulate[widechars]>=0.9.0"] test = [ + { include-group = "typing" }, "cloudpickle>=3.0.0", "deepdiff>=7.0.0", "nbmake>=1.5.5", @@ -73,8 +74,9 @@ test = [ "coiled>=1.42.0; python_version < '3.14'", "networkx>=2.4.0", "pygraphviz>=2.0;platform_system=='Linux'", + "pytest-typing>=26.3.0", ] -typing = ["ty>=0.0.8"] +typing = ["ty>=0.0.91"] [project.urls] Changelog = "https://pytask-dev.readthedocs.io/en/stable/changes.html" @@ -156,6 +158,7 @@ force-single-line = true convention = "numpy" [tool.pytest.ini_options] +typing_checkers = ["ty"] testpaths = ["src", "tests"] filterwarnings = [ "ignore:'@pytask.mark.*. is deprecated:FutureWarning", diff --git a/tests/test_typing_tree_util.md b/tests/test_typing_tree_util.md new file mode 100644 index 00000000..605400d7 --- /dev/null +++ b/tests/test_typing_tree_util.md @@ -0,0 +1,317 @@ +# tree_leaves + +The cases below document the intended leaf types for pytask node trees. When a +checker infers a different type, the snapshot records its current output so +changes can be reviewed against the intended type. + +## Flat dictionary of concrete nodes + +The intended type is `list[PathNode]`. Ty and mypy can infer the entire dictionary +as the leaf. See [ty #2870](https://github.com/astral-sh/ty/issues/2870). + +```python only=ty +from typing_extensions import reveal_type + +from pytask import PathNode +from pytask.tree_util import tree_leaves + + +def check_flat_dict(node: PathNode) -> None: + # revealed: list[dict[str, PathNode]] + reveal_type(tree_leaves({"input": node})) +``` + +```python only=pyright,pyrefly +from typing_extensions import assert_type + +from pytask import PathNode +from pytask.tree_util import tree_leaves + + +def check_flat_dict(node: PathNode) -> None: + assert_type(tree_leaves({"input": node}), list[PathNode]) +``` + +```python only=mypy +from typing_extensions import reveal_type + +from pytask import PathNode +from pytask.tree_util import tree_leaves + + +def check_flat_dict(node: PathNode) -> None: + # revealed: list[dict[Any, _pytask.nodes.PathNode]] + reveal_type(tree_leaves({"input": node})) +``` + +## Custom leaf predicates can treat a container as a leaf + +When the predicate accepts the whole input, the intended leaf type is the +container type, `list[PythonNode]`. + +```python only=ty,pyright,pyrefly +from typing_extensions import reveal_type + +from pytask import PythonNode +from pytask.tree_util import tree_leaves + +nodes = [PythonNode(value="input")] +# revealed: list[list[PythonNode]] +reveal_type(tree_leaves(nodes, is_leaf=lambda value: isinstance(value, list))) +``` + +```python only=mypy +from typing_extensions import reveal_type + +from pytask import PythonNode +from pytask.tree_util import tree_leaves + +nodes = [PythonNode(value="input")] +# revealed: list[list[_pytask.nodes.PythonNode]] +reveal_type(tree_leaves(nodes, is_leaf=lambda value: isinstance(value, list))) +``` + + +## Nested containers of concrete nodes + +Related issues: + +- [ty #2870](https://github.com/astral-sh/ty/issues/2870) +- [Pyright #9798](https://github.com/microsoft/pyright/issues/9798) + +Intended types: + +- `reveal_type(tree_leaves(paths))`: `list[PathNode]`. +- `reveal_type(tree_leaves(objects))`: `list[PythonNode]`. + +Current reveals (ty, pyright, pyrefly): + +```python only=ty,pyright,pyrefly +from pathlib import Path +from typing_extensions import reveal_type + +from pytask import PathNode, PythonNode +from pytask.tree_util import tree_leaves + +paths: dict[str, list[tuple[PathNode, ...]]] = { + "inputs": [(PathNode(path=Path("input.txt")),)], +} +objects: list[dict[str, tuple[PythonNode, ...]]] = [ + {"inputs": (PythonNode(value="input"),)}, +] + +# revealed: list[dict[str, list[tuple[PathNode, ...]]]] +reveal_type(tree_leaves(paths)) +# revealed: list[list[dict[str, tuple[PythonNode, ...]]]] +reveal_type(tree_leaves(objects)) +``` + +Current reveals (mypy): + +```python only=mypy +from pathlib import Path +from typing_extensions import reveal_type + +from pytask import PathNode, PythonNode +from pytask.tree_util import tree_leaves + +paths: dict[str, list[tuple[PathNode, ...]]] = { + "inputs": [(PathNode(path=Path("input.txt")),)], +} +objects: list[dict[str, tuple[PythonNode, ...]]] = [ + {"inputs": (PythonNode(value="input"),)}, +] + +# revealed: list[dict[str, list[tuple[_pytask.nodes.PathNode, ...]]]] +reveal_type(tree_leaves(paths)) +# revealed: list[list[dict[str, tuple[_pytask.nodes.PythonNode, ...]]]] +reveal_type(tree_leaves(objects)) +``` + + +## Trees annotated with the node protocol + +Related issues: + +- [ty #2870](https://github.com/astral-sh/ty/issues/2870) + +Intended types: + +- `reveal_type(leaves)`: `list[PNode]`. +- `reveal_type(node.signature)`: `str`. +- `reveal_type(node.state())`: `str | None`. + +Current reveals (ty): + +Ty reports these attribute errors as `unresolved-attribute` in 0.0.91 and +`missing-union-attribute` in 0.0.107. + +```python only=ty +from typing_extensions import reveal_type + +from pytask import PNode +from pytask.tree_util import PyTree, tree_leaves + + +def check_node_tree(tree: PyTree[PNode]) -> None: + leaves = tree_leaves(tree) + # revealed: list[PNode | tuple[PyTree[PNode], ...] | list[PyTree[PNode]] | dict[Any, PyTree[PNode]]] + reveal_type(leaves) + for node in leaves: + # revealed: str + reveal_type(node.signature) # type: ignore + # revealed: str | None + reveal_type(node.state()) # type: ignore + node.load() # type: ignore +``` + +Current reveals (pyright, pyrefly): + +```python only=pyright,pyrefly +from typing_extensions import reveal_type + +from pytask import PNode +from pytask.tree_util import PyTree, tree_leaves + + +def check_node_tree(tree: PyTree[PNode]) -> None: + leaves = tree_leaves(tree) + # revealed: list[PNode] + reveal_type(leaves) + for node in leaves: + # ty-error: [unresolved-attribute] + # revealed: str + reveal_type(node.signature) + # ty-error: [unresolved-attribute] + # revealed: str | None + reveal_type(node.state()) + # ty-error: [unresolved-attribute] + node.load() +``` + +Current reveals (mypy): + +```python only=mypy +from typing_extensions import reveal_type + +from pytask import PNode +from pytask.tree_util import PyTree, tree_leaves + + +def check_node_tree(tree: PyTree[PNode]) -> None: + leaves = tree_leaves(tree) + # revealed: list[_pytask.node_protocols.PNode] + reveal_type(leaves) + for node in leaves: + # ty-error: [unresolved-attribute] + # revealed: str + reveal_type(node.signature) + # ty-error: [unresolved-attribute] + # revealed: str | None + reveal_type(node.state()) + # ty-error: [unresolved-attribute] + node.load() +``` + + +## Task dependencies and products include provisional nodes + +Plugins receive `PTask`, whose argument dictionaries contain concrete or provisional +nodes. This is a broader contract than `PyTree[PNode]`. + +Related issues: + +- [ty #2870](https://github.com/astral-sh/ty/issues/2870) +- [mypy #6751](https://github.com/python/mypy/issues/6751) +- [mypy #22063](https://github.com/python/mypy/issues/22063) + +Intended types: + +- `reveal_type(tree_leaves(task.depends_on))`: `list[PNode | PProvisionalNode]`. +- `reveal_type(tree_leaves(task.produces))`: `list[PNode | PProvisionalNode]`. + +Current reveals (ty): + +```python only=ty +from typing_extensions import reveal_type + +from pytask import PTask +from pytask.tree_util import tree_leaves + + +def check_task_nodes(task: PTask) -> None: + # revealed: list[dict[str, PNode | PProvisionalNode | tuple[PyTree[PNode | PProvisionalNode], ...] | list[PyTree[PNode | PProvisionalNode]] | dict[Any, PyTree[PNode | PProvisionalNode]]] | PNode | PProvisionalNode | tuple[PyTree[PNode | PProvisionalNode], ...] | list[PyTree[PNode | PProvisionalNode]] | dict[Any, PyTree[PNode | PProvisionalNode]]] + reveal_type(tree_leaves(task.depends_on)) + # revealed: list[dict[str, PNode | PProvisionalNode | tuple[PyTree[PNode | PProvisionalNode], ...] | list[PyTree[PNode | PProvisionalNode]] | dict[Any, PyTree[PNode | PProvisionalNode]]] | PNode | PProvisionalNode | tuple[PyTree[PNode | PProvisionalNode], ...] | list[PyTree[PNode | PProvisionalNode]] | dict[Any, PyTree[PNode | PProvisionalNode]]] + reveal_type(tree_leaves(task.produces)) +``` + +Current reveals (pyright, pyrefly): + +```python only=pyright,pyrefly +from typing_extensions import reveal_type + +from pytask import PTask +from pytask.tree_util import tree_leaves + + +def check_task_nodes(task: PTask) -> None: + # revealed: list[PNode | PProvisionalNode] + reveal_type(tree_leaves(task.depends_on)) + # revealed: list[PNode | PProvisionalNode] + reveal_type(tree_leaves(task.produces)) +``` + +Current reveals (mypy): + +```python only=mypy +from typing_extensions import reveal_type + +from pytask import PTask +from pytask.tree_util import tree_leaves + + +def check_task_nodes(task: PTask) -> None: + # mypy-error: [misc] Cannot infer value of type parameter + # revealed: list[Any] + reveal_type(tree_leaves(task.depends_on)) + # mypy-error: [misc] Cannot infer value of type parameter + # revealed: list[Any] + reveal_type(tree_leaves(task.produces)) +``` + + +## Discover paths in task nodes + +Based on `pytask-latex`'s dependency and product discovery. Narrowing a flattened leaf +to `PPathNode` must allow access to its path without casts or ignores. + +Related issues: + +- [mypy #6751](https://github.com/python/mypy/issues/6751) +- [mypy #22063](https://github.com/python/mypy/issues/22063) + +Intended types: + +- The narrowed path's `as_posix()` result is `str`. + +```python +from typing_extensions import assert_type + +from pytask import PPathNode, PTask +from pytask.tree_util import tree_leaves + + +def check_task_paths(task: PTask) -> set[str]: + paths: set[str] = set() + # mypy-error: [misc] Cannot infer value of type parameter + for node in tree_leaves(task.depends_on): + if isinstance(node, PPathNode): + assert_type(node.path.as_posix(), str) + paths.add(node.path.as_posix()) + # mypy-error: [misc] Cannot infer value of type parameter + for node in tree_leaves(task.produces): + if isinstance(node, PPathNode): + paths.add(node.path.as_posix()) + return paths +``` diff --git a/tests/test_typing_tree_util_plugins.md b/tests/test_typing_tree_util_plugins.md new file mode 100644 index 00000000..1526a901 --- /dev/null +++ b/tests/test_typing_tree_util_plugins.md @@ -0,0 +1,263 @@ +# Tree mapping used by plugins + +These snippets reproduce plugin input annotations, callback signatures, and uses of +the results without depending on the plugins. Assignments and return annotations check +recursive result types; reveals check that the outer task argument keys remain strings. +The snippets are static typing tests, not plugin integration tests. + +## Load task argument trees with paths + +Based on `pytask-parallel`'s `create_kwargs_for_task`. Dependency and product leaves +can be concrete or provisional nodes, and loading them returns arbitrary task values. + +Related issues: + +- [ty #3415](https://github.com/astral-sh/ty/issues/3415) +- [mypy #22063](https://github.com/python/mypy/issues/22063) + +```python +from typing import Any + +from pytask import PNode, PProvisionalNode, PTask +from pytask.tree_util import PyTree, tree_map_with_path + + +def load_node(path: tuple[Any, ...], node: PNode | PProvisionalNode) -> Any: + return node.load(is_product=path[0] == "produces") + + +def create_kwargs(task: PTask) -> dict[str, PyTree[Any]]: + kwargs: dict[str, PyTree[Any]] = {} + for name, tree in task.depends_on.items(): + kwargs[name] = tree_map_with_path( + lambda path, node: load_node((name, *path), node), tree + ) + for name, tree in task.produces.items(): + kwargs[name] = tree_map_with_path( + lambda path, node: load_node((name, *path), node), tree + ) + return kwargs +``` + +## Carry products from a worker + +Based on `pytask-parallel`'s product handling. `CarryOverPath` reproduces the plugin's +named tuple declaration. Product mapping changes leaf types and can return `None`. + +Related issues: + +- [ty #3415](https://github.com/astral-sh/ty/issues/3415) +- [mypy #22063](https://github.com/python/mypy/issues/22063) + +Intended types: + +- `list(mapped)`: `list[str]`. + +```python +from typing import Any, NamedTuple +from typing_extensions import assert_type + +from pytask import PNode, PPathNode, PTask, PythonNode +from pytask.tree_util import PyTree, tree_map_with_path + + +class CarryOverPath(NamedTuple): + content: bytes + + +def carry_product( + path: tuple[Any, ...], node: PNode +) -> CarryOverPath | PythonNode | None: + if isinstance(node, PythonNode): + return node + if isinstance(node, PPathNode): + return CarryOverPath(content=node.path.read_bytes()) + return None + + +def carry_products(task: PTask) -> dict[str, PyTree[CarryOverPath | PythonNode | None]]: + # mypy-error: [misc] Cannot infer value of type parameter + mapped = tree_map_with_path(carry_product, task.produces) + assert_type(list(mapped), list[str]) + return mapped +``` + + +## Update products from a corresponding carry-over tree + +Based on `pytask-parallel`'s `_update_carry_over_products`. The two trees have +different leaf types. The mapped result must retain its task argument dictionary +and be assignable to `task.produces`. + +Related issues: + +- [ty #3415](https://github.com/astral-sh/ty/issues/3415) +- [mypy #22063](https://github.com/python/mypy/issues/22063) + +Intended types: + +- `list(mapped)`: `list[str]`. + +```python +from typing import NamedTuple +from typing_extensions import assert_type + +from pytask import PNode, PTask, PythonNode +from pytask.tree_util import PyTree, tree_map + + +class CarryOverPath(NamedTuple): + content: bytes + + +def update_node(node: PNode, carried: CarryOverPath | PythonNode | None) -> PNode: + if isinstance(carried, PythonNode): + node.save(carried.load()) + return node + + +def update_products( + task: PTask, carried: PyTree[CarryOverPath | PythonNode | None] +) -> None: + # mypy-error: [misc] Cannot infer value of type parameter + mapped = tree_map(update_node, task.produces, carried) + assert_type(list(mapped), list[str]) + task.produces = mapped +``` + + +## Resolve remote nodes in task keyword arguments + +Based on `pytask-parallel`'s `_write_local_files_to_remote`. The minimal custom node +declares the plugin's `load` return type; other node operations come from `PNode`. +Task values must remain supported even when they are no longer nodes. + +Related issues: + +- [Pyrefly #4910](https://github.com/facebook/pyrefly/issues/4910) +- [mypy #15750](https://github.com/python/mypy/issues/15750) + +Intended types: + +- `reveal_type(list(mapped))`: `list[str]`. + +Current reveals (ty, pyright): + +```python only=ty,pyright +from pathlib import Path +from typing import Any +from typing_extensions import reveal_type + +from pytask import PNode +from pytask.tree_util import PyTree, tree_map + + +class RemotePathNode(PNode): + def load(self, is_product: bool = False) -> Path: + raise NotImplementedError + + +def resolve_remote_values(kwargs: dict[str, PyTree[Any]]) -> dict[str, PyTree[Any]]: + mapped = tree_map( + lambda value: value.load() if isinstance(value, RemotePathNode) else value, + kwargs, + ) + # revealed: list[str] + reveal_type(list(mapped)) + return mapped +``` + +Current reveals (pyrefly): + +```python only=pyrefly +from pathlib import Path +from typing import Any +from typing_extensions import reveal_type + +from pytask import PNode +from pytask.tree_util import PyTree, tree_map + + +class RemotePathNode(PNode): + def load(self, is_product: bool = False) -> Path: + raise NotImplementedError + + +def resolve_remote_values(kwargs: dict[str, PyTree[Any]]) -> dict[str, PyTree[Any]]: + mapped = tree_map( + lambda value: value.load() if isinstance(value, RemotePathNode) else value, + kwargs, + ) + # revealed: list[Unknown] + reveal_type(list(mapped)) + return mapped +``` + +Current reveals (mypy): + +```python only=mypy +from pathlib import Path +from typing import Any +from typing_extensions import reveal_type + +from pytask import PNode +from pytask.tree_util import PyTree, tree_map + + +class RemotePathNode(PNode): + def load(self, is_product: bool = False) -> Path: + raise NotImplementedError + + +def resolve_remote_values(kwargs: dict[str, PyTree[Any]]) -> dict[str, PyTree[Any]]: + mapped = tree_map( + lambda value: value.load() if isinstance(value, RemotePathNode) else value, + kwargs, + ) + # revealed: list[Any] + reveal_type(list(mapped)) + return mapped +``` + + +## Unpack mapped dependencies and products as keyword arguments + +Based on the Julia, R, and Stata plugins' keyword argument collection. A path node +becomes a string; other leaves expose their Python value. Both mapped results must +support dictionary unpacking. + +Related issues: + +- [ty #3415](https://github.com/astral-sh/ty/issues/3415) +- [mypy #15750](https://github.com/python/mypy/issues/15750) + +Intended types: + +- `list(kwargs)`: `list[str]`. + +```python +from typing import Any +from typing_extensions import assert_type + +from pytask import PPathNode, PTask +from pytask.tree_util import tree_map + + +def collect_kwargs(task: PTask) -> dict[str, Any]: + kwargs = { + **tree_map( + lambda node: ( + node.path.as_posix() if isinstance(node, PPathNode) else node.value + ), + task.depends_on, + ), + **tree_map( + lambda node: ( + node.path.as_posix() if isinstance(node, PPathNode) else node.value + ), + task.produces, + ), + } + assert_type(list(kwargs), list[str]) + return kwargs +``` diff --git a/tests/test_typing_tree_util_structure.md b/tests/test_typing_tree_util_structure.md new file mode 100644 index 00000000..034605e2 --- /dev/null +++ b/tests/test_typing_tree_util_structure.md @@ -0,0 +1,365 @@ +# tree_structure + +Structure queries must accept node trees and return a usable `PyTreeSpec`, without +requiring casts of task dependencies or products. + +## Concrete nodes in flat and nested containers + +```python +from optree import PyTreeSpec +from pytask import PathNode, PythonNode +from pytask.tree_util import tree_structure + + +def check_structures(path_node: PathNode, python_node: PythonNode) -> None: + single: PyTreeSpec = tree_structure(path_node) + listed: PyTreeSpec = tree_structure([python_node]) + paired: PyTreeSpec = tree_structure((path_node, python_node)) + named: PyTreeSpec = tree_structure({"input": path_node}) + nested: PyTreeSpec = tree_structure({"inputs": [(path_node, python_node)]}) +``` + +## Compare task return and worker product structures + +Based on pytask's return validation and pytask-parallel's return validation and +carry-over product updates. The comparison must work without casting either tree. + +Intended types: + +- `declared.is_prefix(output, strict=False)`: `bool`. +- `products.is_prefix(worker_products, strict=False)`: `bool`. + +```python +from typing import Any +from typing_extensions import assert_type + +from optree import PyTreeSpec +from pytask import PTask +from pytask.tree_util import PyTree, tree_structure + + +def check_task_structures(task: PTask, out: Any, carried: PyTree[Any]) -> None: + output: PyTreeSpec = tree_structure(out) + declared: PyTreeSpec = tree_structure(task.produces["return"]) + assert_type(declared.is_prefix(output, strict=False), bool) + products: PyTreeSpec = tree_structure(task.produces) + worker_products: PyTreeSpec = tree_structure(carried) + assert_type(products.is_prefix(worker_products, strict=False), bool) + dependencies: PyTreeSpec = tree_structure(task.depends_on) +``` + + +# tree_flatten_with_path + +Flattening must preserve node leaf types and expose paths and a usable structure. + +## Concrete nodes in different containers + +Related issues: + +- [ty #2870](https://github.com/astral-sh/ty/issues/2870) + +Intended types: + +- `reveal_type(paths)`: `list[tuple[Any, ...]]`. +- `reveal_type(leaves)`: `list[PathNode]`. +- `reveal_type(tree_flatten_with_path([path_node])[1])`: `list[PathNode]`. +- `reveal_type(tree_flatten_with_path((path_node,))[1])`: `list[PathNode]`. +- `reveal_type(tree_flatten_with_path({"input": path_node})[1])`: `list[PathNode]`. +- `reveal_type(tree_flatten_with_path(python_node)[1])`: `list[PythonNode]`. +- `reveal_type(tree_flatten_with_path([python_node])[1])`: `list[PythonNode]`. +- `reveal_type(tree_flatten_with_path((python_node,))[1])`: `list[PythonNode]`. +- `reveal_type(tree_flatten_with_path({"input": python_node})[1])`: `list[PythonNode]`. + +Current reveals (ty): + +```python only=ty +from typing_extensions import reveal_type + +from optree import PyTreeSpec +from pytask import PathNode, PythonNode +from pytask.tree_util import tree_flatten_with_path + + +def check_flattened_nodes(path_node: PathNode, python_node: PythonNode) -> None: + paths, leaves, spec = tree_flatten_with_path(path_node) + # revealed: list[tuple[Any, ...]] + reveal_type(paths) + # revealed: list[PathNode] + reveal_type(leaves) + structure: PyTreeSpec = spec + # revealed: list[list[PathNode]] + reveal_type(tree_flatten_with_path([path_node])[1]) + # revealed: list[tuple[PathNode] | PathNode] + reveal_type(tree_flatten_with_path((path_node,))[1]) + # revealed: list[dict[str, PathNode]] + reveal_type(tree_flatten_with_path({"input": path_node})[1]) + # revealed: list[PythonNode] + reveal_type(tree_flatten_with_path(python_node)[1]) + # revealed: list[list[PythonNode]] + reveal_type(tree_flatten_with_path([python_node])[1]) + # revealed: list[tuple[PythonNode] | PythonNode] + reveal_type(tree_flatten_with_path((python_node,))[1]) + # revealed: list[dict[str, PythonNode]] + reveal_type(tree_flatten_with_path({"input": python_node})[1]) +``` + +Current reveals (pyright, pyrefly): + +```python only=pyright,pyrefly +from typing_extensions import reveal_type + +from optree import PyTreeSpec +from pytask import PathNode, PythonNode +from pytask.tree_util import tree_flatten_with_path + + +def check_flattened_nodes(path_node: PathNode, python_node: PythonNode) -> None: + paths, leaves, spec = tree_flatten_with_path(path_node) + # revealed: list[tuple[Any, ...]] + reveal_type(paths) + # revealed: list[PathNode] + reveal_type(leaves) + structure: PyTreeSpec = spec + # revealed: list[PathNode] + reveal_type(tree_flatten_with_path([path_node])[1]) + # revealed: list[PathNode] + reveal_type(tree_flatten_with_path((path_node,))[1]) + # revealed: list[PathNode] + reveal_type(tree_flatten_with_path({"input": path_node})[1]) + # revealed: list[PythonNode] + reveal_type(tree_flatten_with_path(python_node)[1]) + # revealed: list[PythonNode] + reveal_type(tree_flatten_with_path([python_node])[1]) + # revealed: list[PythonNode] + reveal_type(tree_flatten_with_path((python_node,))[1]) + # revealed: list[PythonNode] + reveal_type(tree_flatten_with_path({"input": python_node})[1]) +``` + +Current reveals (mypy): + +```python only=mypy +from typing_extensions import reveal_type + +from optree import PyTreeSpec +from pytask import PathNode, PythonNode +from pytask.tree_util import tree_flatten_with_path + + +def check_flattened_nodes(path_node: PathNode, python_node: PythonNode) -> None: + paths, leaves, spec = tree_flatten_with_path(path_node) + # revealed: list[tuple[Any, ...]] + reveal_type(paths) + # revealed: list[_pytask.nodes.PathNode] + reveal_type(leaves) + structure: PyTreeSpec = spec + # revealed: list[list[_pytask.nodes.PathNode]] + reveal_type(tree_flatten_with_path([path_node])[1]) + # revealed: list[_pytask.nodes.PathNode] + reveal_type(tree_flatten_with_path((path_node,))[1]) + # revealed: list[dict[Any, _pytask.nodes.PathNode]] + reveal_type(tree_flatten_with_path({"input": path_node})[1]) + # revealed: list[_pytask.nodes.PythonNode] + reveal_type(tree_flatten_with_path(python_node)[1]) + # revealed: list[list[_pytask.nodes.PythonNode]] + reveal_type(tree_flatten_with_path([python_node])[1]) + # revealed: list[_pytask.nodes.PythonNode] + reveal_type(tree_flatten_with_path((python_node,))[1]) + # revealed: list[dict[Any, _pytask.nodes.PythonNode]] + reveal_type(tree_flatten_with_path({"input": python_node})[1]) +``` + + +## Nested containers of concrete nodes + +Related issues: + +- [ty #2870](https://github.com/astral-sh/ty/issues/2870) +- [Pyright #9798](https://github.com/microsoft/pyright/issues/9798) + +Intended types: + +- `reveal_type(tree_flatten_with_path(paths)[1])`: `list[PathNode]`. +- `reveal_type(tree_flatten_with_path(objects)[1])`: `list[PythonNode]`. + +Current reveals (ty, pyright, pyrefly): + +```python only=ty,pyright,pyrefly +from typing_extensions import reveal_type + +from pytask import PathNode, PythonNode +from pytask.tree_util import tree_flatten_with_path + + +def check_nested_nodes( + paths: dict[str, list[tuple[PathNode, ...]]], + objects: list[dict[str, tuple[PythonNode, ...]]], +) -> None: + # revealed: list[dict[str, list[tuple[PathNode, ...]]]] + reveal_type(tree_flatten_with_path(paths)[1]) + # revealed: list[list[dict[str, tuple[PythonNode, ...]]]] + reveal_type(tree_flatten_with_path(objects)[1]) +``` + +Current reveals (mypy): + +```python only=mypy +from typing_extensions import reveal_type + +from pytask import PathNode, PythonNode +from pytask.tree_util import tree_flatten_with_path + + +def check_nested_nodes( + paths: dict[str, list[tuple[PathNode, ...]]], + objects: list[dict[str, tuple[PythonNode, ...]]], +) -> None: + # revealed: list[dict[str, list[tuple[_pytask.nodes.PathNode, ...]]]] + reveal_type(tree_flatten_with_path(paths)[1]) + # revealed: list[list[dict[str, tuple[_pytask.nodes.PythonNode, ...]]]] + reveal_type(tree_flatten_with_path(objects)[1]) +``` + + +## Protocol trees and task dependencies and products + +Related issues: + +- [ty #2870](https://github.com/astral-sh/ty/issues/2870) +- [mypy #6751](https://github.com/python/mypy/issues/6751) + +Intended types: + +- `reveal_type(paths)`: `list[tuple[Any, ...]]`. +- `reveal_type(leaves)`: `list[PNode]`. +- `reveal_type(tree_flatten_with_path(task.depends_on)[1])`: `list[PNode | PProvisionalNode]`. +- `reveal_type(tree_flatten_with_path(task.produces)[1])`: `list[PNode | PProvisionalNode]`. + +Current reveals (ty): + +```python only=ty +from typing_extensions import reveal_type + +from pytask import PNode, PTask +from pytask.tree_util import PyTree, tree_flatten_with_path + + +def check_protocol_trees(tree: PyTree[PNode], task: PTask) -> None: + paths, leaves, spec = tree_flatten_with_path(tree) + # revealed: list[tuple[Any, ...]] + reveal_type(paths) + # revealed: list[PNode | tuple[PyTree[PNode], ...] | list[PyTree[PNode]] | dict[Any, PyTree[PNode]]] + reveal_type(leaves) + # mypy-error: [misc] Cannot infer value of type parameter + # revealed: list[dict[str, PNode | PProvisionalNode | tuple[PyTree[PNode | PProvisionalNode], ...] | list[PyTree[PNode | PProvisionalNode]] | dict[Any, PyTree[PNode | PProvisionalNode]]] | PNode | PProvisionalNode | tuple[PyTree[PNode | PProvisionalNode], ...] | list[PyTree[PNode | PProvisionalNode]] | dict[Any, PyTree[PNode | PProvisionalNode]]] + reveal_type(tree_flatten_with_path(task.depends_on)[1]) + # mypy-error: [misc] Cannot infer value of type parameter + # revealed: list[dict[str, PNode | PProvisionalNode | tuple[PyTree[PNode | PProvisionalNode], ...] | list[PyTree[PNode | PProvisionalNode]] | dict[Any, PyTree[PNode | PProvisionalNode]]] | PNode | PProvisionalNode | tuple[PyTree[PNode | PProvisionalNode], ...] | list[PyTree[PNode | PProvisionalNode]] | dict[Any, PyTree[PNode | PProvisionalNode]]] + reveal_type(tree_flatten_with_path(task.produces)[1]) +``` + +Current reveals (pyright, pyrefly): + +```python only=pyright,pyrefly +from typing_extensions import reveal_type + +from pytask import PNode, PTask +from pytask.tree_util import PyTree, tree_flatten_with_path + + +def check_protocol_trees(tree: PyTree[PNode], task: PTask) -> None: + paths, leaves, spec = tree_flatten_with_path(tree) + # revealed: list[tuple[Any, ...]] + reveal_type(paths) + # revealed: list[PNode] + reveal_type(leaves) + # mypy-error: [misc] Cannot infer value of type parameter + # revealed: list[PNode | PProvisionalNode] + reveal_type(tree_flatten_with_path(task.depends_on)[1]) + # mypy-error: [misc] Cannot infer value of type parameter + # revealed: list[PNode | PProvisionalNode] + reveal_type(tree_flatten_with_path(task.produces)[1]) +``` + +Current reveals (mypy): + +```python only=mypy +from typing_extensions import reveal_type + +from pytask import PNode, PTask +from pytask.tree_util import PyTree, tree_flatten_with_path + + +def check_protocol_trees(tree: PyTree[PNode], task: PTask) -> None: + paths, leaves, spec = tree_flatten_with_path(tree) + # revealed: list[tuple[Any, ...]] + reveal_type(paths) + # revealed: list[_pytask.node_protocols.PNode] + reveal_type(leaves) + # mypy-error: [misc] Cannot infer value of type parameter + # revealed: list[Any] + reveal_type(tree_flatten_with_path(task.depends_on)[1]) + # mypy-error: [misc] Cannot infer value of type parameter + # revealed: list[Any] + reveal_type(tree_flatten_with_path(task.produces)[1]) +``` + + +## A custom predicate can make a container a leaf + +Intended types: + +- `reveal_type(paths)`: `list[tuple[Any, ...]]`. +- `reveal_type(leaves)`: `list[list[PythonNode]]`. +- `reveal_type(structure.is_prefix(spec, strict=False))`: `bool`. + +Current reveals (ty, pyright, pyrefly): + +```python only=ty,pyright,pyrefly +from typing_extensions import reveal_type + +from optree import PyTreeSpec +from pytask import PythonNode +from pytask.tree_util import tree_flatten_with_path, tree_structure + + +def check_container_leaf(nodes: list[PythonNode]) -> None: + paths, leaves, spec = tree_flatten_with_path( + nodes, is_leaf=lambda value: isinstance(value, list) + ) + # revealed: list[tuple[Any, ...]] + reveal_type(paths) + # revealed: list[list[PythonNode]] + reveal_type(leaves) + structure: PyTreeSpec = tree_structure( + nodes, is_leaf=lambda value: isinstance(value, list) + ) + # revealed: bool + reveal_type(structure.is_prefix(spec, strict=False)) +``` + +Current reveals (mypy): + +```python only=mypy +from typing_extensions import reveal_type + +from optree import PyTreeSpec +from pytask import PythonNode +from pytask.tree_util import tree_flatten_with_path, tree_structure + + +def check_container_leaf(nodes: list[PythonNode]) -> None: + paths, leaves, spec = tree_flatten_with_path( + nodes, is_leaf=lambda value: isinstance(value, list) + ) + # revealed: list[tuple[Any, ...]] + reveal_type(paths) + # revealed: list[list[_pytask.nodes.PythonNode]] + reveal_type(leaves) + structure: PyTreeSpec = tree_structure( + nodes, is_leaf=lambda value: isinstance(value, list) + ) + # revealed: bool + reveal_type(structure.is_prefix(spec, strict=False)) +``` diff --git a/uv.lock b/uv.lock index 707a074b..648a83a8 100644 --- a/uv.lock +++ b/uv.lock @@ -3063,8 +3063,10 @@ test = [ { name = "pygraphviz", marker = "sys_platform == 'linux'" }, { name = "pytest" }, { name = "pytest-cov" }, + { name = "pytest-typing" }, { name = "pytest-xdist" }, { name = "syrupy" }, + { name = "ty" }, ] typing = [ { name = "ty" }, @@ -3114,10 +3116,12 @@ test = [ { name = "pygraphviz", marker = "sys_platform == 'linux'", specifier = ">=2.0" }, { name = "pytest", specifier = ">=8.4.0" }, { name = "pytest-cov", specifier = ">=5.0.0" }, + { name = "pytest-typing", specifier = ">=26.3.0" }, { name = "pytest-xdist", specifier = ">=3.6.1" }, { name = "syrupy", specifier = ">=4.5.0" }, + { name = "ty", specifier = ">=0.0.91" }, ] -typing = [{ name = "ty", specifier = ">=0.0.8" }] +typing = [{ name = "ty", specifier = ">=0.0.91" }] [[package]] name = "pytest" @@ -3149,6 +3153,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/9d/7a/d968e294073affff457b041c2be9868a40c1c71f4a35fcc1e45e5493067b/pytest_cov-7.1.0-py3-none-any.whl", hash = "sha256:a0461110b7865f9a271aa1b51e516c9a95de9d696734a2f71e3e78f46e1d4678", size = 22876, upload-time = "2026-03-21T20:11:14.438Z" }, ] +[[package]] +name = "pytest-typing" +version = "26.5.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ce/40/88fdd6dd1c4c2dd632b6b6b278160d411a396c720f4c9e4e7d17d93f7633/pytest_typing-26.5.0.tar.gz", hash = "sha256:102858c2a93b9d077996e259f399eebb3458fd019c474f936847517f0e0b2523", size = 66470, upload-time = "2026-10-13T22:03:54.301Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6b/19/26b8f3a4f0c67dc95041fb1475e761f47974e88c800d410fa21bec6bf5bd/pytest_typing-26.5.0-py3-none-any.whl", hash = "sha256:96ad768a7aa7ee71a8ec6c85c3c330101f6be4bc091f400e54c98d9a6b46364f", size = 18043, upload-time = "2026-10-13T22:03:53.145Z" }, +] + [[package]] name = "pytest-xdist" version = "3.8.0"