Coverage for src/remedapy/prop.py: 72%

1 from collections.abc import Callable, Sequence

2 from typing import Any, TypeVar, overload

3

4 Key = str | int

5 T = TypeVar('T')

6

7

8@overload

9 def prop(data: dict[Key, T], /, key: Key) -> T | None: ...

10

11

12@overload

13 def prop(data: Sequence[T], /, key: int) -> T | None: ...

14

15

16@overload

17 def prop(key: str, /) -> Callable[[dict[str, T]], T | None]: ...

18

19

20@overload

21 def prop(key: int, /) -> Callable[[Sequence[T]], T | None]: ...

22

23

24@overload

25 def prop(data: dict[Key, Any], /, *keys: Key) -> Any | None: ...

26

27

28@overload

29 def prop(data: Sequence[Any], /, *keys: int | str) -> Any | None: ...

30

31

32@overload

33 def prop(*keys: int | str) -> Any | None: ...

34

35

36 def prop_helper(data: Any, /, *keys: int | str) -> Any | None:

37 if len(keys) == 0:

38 return data

39 try:

40 new_data = data[keys[0]]

41 except KeyError:

42 return None

43 except IndexError:

44 return None

45 return prop_helper(new_data, *keys[1:])

46

47

48 def prop(data: Any, /, *keys: int | str) -> Any | None: # pyright: ignore[reportInconsistentOverload]

49 if not isinstance(data, (dict, list, tuple)):

50 return lambda x: prop_helper(x, data, *keys) # pyright: ignore[reportUnknownVariableType, reportUnknownLambdaType]

51 return prop_helper(data, keys) # pyright: ignore[reportArgumentType]