Coverage for bioimageio/spec/_internal/type_guards.py: 90%

21 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-11 07:34 +0000

1"""use these type guards with caution! 

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

3 

4import collections.abc 

5from typing import Any, Dict, List, Mapping, Sequence, Set, Tuple 

6 

7import numpy as np 

8from numpy.typing import NDArray 

9from typing_extensions import TypeGuard 

10 

11 

12def is_dict(v: Any) -> TypeGuard[Dict[Any, Any]]: 

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

14 return isinstance(v, dict) 

15 

16 

17def is_set(v: Any) -> TypeGuard[Set[Any]]: 

18 """to avoid Set[Unknown]""" 

19 return isinstance(v, set) 

20 

21 

22def is_kwargs(v: Any) -> TypeGuard[Dict[str, Any]]: 

23 return isinstance(v, dict) and all( 

24 isinstance(k, str) 

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

26 ) 

27 

28 

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

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

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

32 

33 

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

35 """to avoid Sequence[Unknown]""" 

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

37 

38 

39def is_tuple(v: Any) -> TypeGuard[Tuple[Any, ...]]: 

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

41 return isinstance(v, tuple) 

42 

43 

44def is_list(v: Any) -> TypeGuard[List[Any]]: 

45 """to avoid List[Unknown]""" 

46 return isinstance(v, list) 

47 

48 

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

50 return isinstance(v, np.ndarray)