Coverage for src/pydantic_typer/utils.py: 100%

1 from __future__ import annotations

2

3 import inspect

4 import sys

5 from typing import Any, Callable, TypeVar, get_type_hints

6

7 KeyType = TypeVar("KeyType")

8

9

10 def deep_update(mapping: dict[KeyType, Any], *updating_mappings: dict[KeyType, Any]) -> dict[KeyType, Any]:

11 # Copied from pydantic because they don't expose it publicly:

12 # https://github.com/pydantic/pydantic/blob/26129479a06960af9d02d3a948e51985fe59ed4b/pydantic/_internal/_utils.py#L103

13 updated_mapping = mapping.copy()

14 for updating_mapping in updating_mappings:

15 for k, v in updating_mapping.items():

16 if k in updated_mapping and isinstance(updated_mapping[k], dict) and isinstance(v, dict):

17 updated_mapping[k] = deep_update(updated_mapping[k], v)

18 else:

19 updated_mapping[k] = v

20 return updated_mapping

21

22

23 def _get_type_hints(func: Callable[..., Any]): # pragma: no cover

24 if sys.version_info >= (3, 9):

25 hints = get_type_hints(func, include_extras=True)

26 else:

27 hints = get_type_hints(func)

28 return hints

29

30

31 def inspect_signature(func: Callable[..., Any]) -> inspect.Signature: # pragma: no cover

32 if sys.version_info >= (3, 10):

33 signature = inspect.signature(func, eval_str=True)

34 else:

35 raw_signature = inspect.signature(func)

36 type_hints = _get_type_hints(func)

37 resolved_params = []

38 for p in raw_signature.parameters:

39 old_param = raw_signature.parameters[p]

40 resolved_params.append(

41 inspect.Parameter(old_param.name, old_param.kind, default=old_param.default, annotation=type_hints[p])

42 )

43

44 signature = raw_signature.replace(parameters=resolved_params)

45 return signature

46

47

48 _T = TypeVar("_T")

49

50

51 def copy_type(_: _T) -> Callable[[Any], _T]:

52 """Source https://github.com/python/typing/issues/769#issuecomment-903760354"""

53 return lambda x: x