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

22 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-08-18 09:17 +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 

6import collections.abc 

7from typing import Any, Mapping, Sequence 

8 

9import numpy as np 

10from numpy.typing import NDArray 

11from typing_extensions import TypeGuard 

12 

13 

14def is_dict(v: Any) -> TypeGuard[dict[Any, Any]]: 

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

16 return isinstance(v, dict) 

17 

18 

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

20 """to avoid Set[Unknown]""" 

21 return isinstance(v, set) 

22 

23 

24def is_kwargs(v: Any) -> TypeGuard[dict[str, Any]]: 

25 return isinstance(v, dict) and all( 

26 isinstance(k, str) 

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

28 ) 

29 

30 

31def is_mapping(v: Any) -> TypeGuard[Mapping[Any, Any]]: 

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

33 return isinstance(v, collections.abc.Mapping) 

34 

35 

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

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

38 return isinstance(v, collections.abc.Sequence) 

39 

40 

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

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)