Coverage for src/bioimageio/spec/_internal/type_guards.py: 100%
24 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 16:20 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 16:20 +0000
1"""use these type guards with caution!
2They widen the type to T[Any], which is not always correct."""
4from __future__ import annotations
6from collections.abc import Hashable, Mapping, Sequence
7from typing import Any, TypeGuard, TypeVar
9import numpy as np
10from numpy.typing import NDArray
12T = TypeVar("T")
13K = TypeVar("K", bound=Hashable)
14V = TypeVar("V")
17def is_dict(v: Any | Mapping[K, V]) -> TypeGuard[dict[K, V]]:
18 """to avoid Dict[Unknown, Unknown]"""
19 return isinstance(v, dict)
22def is_set(v: Any) -> TypeGuard[set[Any]]:
23 """to avoid Set[Unknown]"""
24 return isinstance(v, set)
27def is_kwargs(v: Any | Mapping[Any, T]) -> TypeGuard[Mapping[str, T]]:
28 return is_mapping(v) and all(isinstance(k, str) for k in v)
31def is_mapping(value: Any | Mapping[K, V]) -> TypeGuard[Mapping[K, V]]:
32 return isinstance(value, Mapping)
35def is_sequence(v: Any | Sequence[T]) -> TypeGuard[Sequence[T]]:
36 """to avoid Sequence[Unknown]"""
37 return isinstance(v, Sequence)
40def is_tuple(v: Any | Sequence[T]) -> TypeGuard[tuple[T, ...]]:
41 """to avoid Tuple[Unknown, ...]"""
42 return isinstance(v, tuple)
45def is_list(v: Any) -> TypeGuard[list[Any]]:
46 """to avoid List[Unknown]"""
47 return isinstance(v, list)
50def is_ndarray(v: Any) -> TypeGuard[NDArray[Any]]:
51 return isinstance(v, np.ndarray)