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

25 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-10-16 10:20 +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 is_mapping(v) and all(isinstance(k, str) for k in v) 

30 

31 

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

33 return isinstance(value, Mapping) 

34 

35 

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

37 """to avoid Sequence[Unknown]""" 

38 return isinstance(v, Sequence) 

39 

40 

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

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

43 return isinstance(v, tuple) 

44 

45 

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

47 """to avoid List[Unknown]""" 

48 return isinstance(v, list) 

49 

50 

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

52 return isinstance(v, np.ndarray)