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

21 statements  

« prev     ^ index     » next       coverage.py v7.9.1, created at 2025-06-27 09:20 +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) for k in v # pyright: ignore[reportUnknownVariableType] 

25 ) 

26 

27 

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

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

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

31 

32 

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

34 """to avoid Sequence[Unknown]""" 

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

36 

37 

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

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

40 return isinstance(v, tuple) 

41 

42 

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

44 """to avoid List[Unknown]""" 

45 return isinstance(v, list) 

46 

47 

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

49 return isinstance(v, np.ndarray)