Coverage for src/bioimageio/spec/_internal/type_guards.py: 100%

25 statements  

« prev     ^ index     » next       coverage.py v7.16.1, created at 2026-09-15 12:09 +0000

1"""use these type guards with caution! 

2They widen the type to T[Any], which is not always correct.""" 

3 

4from __future__ import annotations 

5 

6from collections.abc import Mapping, Sequence 

7from typing import Any, Hashable, TypeVar 

8 

9import numpy as np 

10from numpy.typing import NDArray 

11from typing_extensions import TypeGuard 

12 

13T = TypeVar("T") 

14K = TypeVar("K", bound=Hashable) 

15V = TypeVar("V") 

16 

17 

18def is_dict(v: Any | Mapping[K, V]) -> TypeGuard[dict[K, V]]: 

19 """to avoid Dict[Unknown, Unknown]""" 

20 return isinstance(v, dict) 

21 

22 

23def is_set(v: Any) -> TypeGuard[set[Any]]: 

24 """to avoid Set[Unknown]""" 

25 return isinstance(v, set) 

26 

27 

28def is_kwargs(v: Any | Mapping[Any, T]) -> TypeGuard[Mapping[str, T]]: 

29 return isinstance(v, Mapping) and all( 

30 isinstance(k, str) 

31 for k in v # pyright: ignore[reportUnknownVariableType] 

32 ) 

33 

34 

35def is_mapping(v: Any | Mapping[K, V]) -> TypeGuard[Mapping[K, V]]: 

36 """to avoid Mapping[Unknown, Unknown]""" 

37 return isinstance(v, Mapping) 

38 

39 

40def is_sequence(v: Any | Sequence[T]) -> TypeGuard[Sequence[T]]: 

41 """to avoid Sequence[Unknown]""" 

42 return isinstance(v, Sequence) 

43 

44 

45def is_tuple(v: Any | Sequence[T]) -> TypeGuard[tuple[T, ...]]: 

46 """to avoid Tuple[Unknown, ...]""" 

47 return isinstance(v, tuple) 

48 

49 

50def is_list(v: Any) -> TypeGuard[list[Any]]: 

51 """to avoid List[Unknown]""" 

52 return isinstance(v, list) 

53 

54 

55def is_ndarray(v: Any) -> TypeGuard[NDArray[Any]]: 

56 return isinstance(v, np.ndarray)