[Misc] Improve type annotations for jsontree (#25577)

Signed-off-by: DarkLight1337 <tlleungac@connect.ust.hk>
This commit is contained in:
Cyrus Leung
2025-09-24 22:49:58 +08:00
committed by GitHub
parent 8938774c79
commit 9313be5017
5 changed files with 88 additions and 39 deletions
+64 -5
View File
@@ -4,7 +4,7 @@
from collections.abc import Iterable
from functools import reduce
from typing import Callable, TypeVar, Union, overload
from typing import Callable, TypeVar, Union, cast, overload
_T = TypeVar("_T")
_U = TypeVar("_U")
@@ -30,10 +30,42 @@ def json_iter_leaves(value: JSONTree[_T]) -> Iterable[_T]:
yield value
@overload
def json_map_leaves(
func: Callable[[_T], _U],
value: Union[_T, dict[str, _T]],
) -> Union[_U, dict[str, _U]]:
...
@overload
def json_map_leaves(
func: Callable[[_T], _U],
value: Union[_T, list[_T]],
) -> Union[_U, list[_U]]:
...
@overload
def json_map_leaves(
func: Callable[[_T], _U],
value: Union[_T, tuple[_T, ...]],
) -> Union[_U, tuple[_U, ...]]:
...
@overload
def json_map_leaves(
func: Callable[[_T], _U],
value: JSONTree[_T],
) -> JSONTree[_U]:
...
def json_map_leaves(
func: Callable[[_T], _U],
value: Union[dict[str, _T], list[_T], tuple[_T, ...], JSONTree[_T]],
) -> Union[dict[str, _U], list[_U], tuple[_U, ...], JSONTree[_U]]:
"""Apply a function to each leaf in a nested JSON structure."""
if isinstance(value, dict):
return {k: json_map_leaves(func, v) for k, v in value.items()}
@@ -45,6 +77,33 @@ def json_map_leaves(
return func(value)
@overload
def json_reduce_leaves(
func: Callable[[_T, _T], _T],
value: Union[_T, dict[str, _T]],
/,
) -> _T:
...
@overload
def json_reduce_leaves(
func: Callable[[_T, _T], _T],
value: Union[_T, list[_T]],
/,
) -> _T:
...
@overload
def json_reduce_leaves(
func: Callable[[_T, _T], _T],
value: Union[_T, tuple[_T, ...]],
/,
) -> _T:
...
@overload
def json_reduce_leaves(
func: Callable[[_T, _T], _T],
@@ -65,10 +124,10 @@ def json_reduce_leaves(
def json_reduce_leaves(
func: Callable[..., Union[_T, _U]],
value: JSONTree[_T],
initial: _U = ..., # type: ignore[assignment]
/,
func: Callable[..., Union[_T, _U]],
value: Union[dict[str, _T], list[_T], tuple[_T, ...], JSONTree[_T]],
initial: _U = cast(_U, ...), # noqa: B008
/,
) -> Union[_T, _U]:
"""
Apply a function of two arguments cumulatively to each leaf in a