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

21 statements  

« prev     ^ index     » next       coverage.py v7.6.0, created at 2024-08-01 16:55 +0200

1from __future__ import annotations 

2 

3import inspect 

4import sys 

5from typing import Any, Callable, TypeVar, get_type_hints 

6 

7KeyType = TypeVar("KeyType") 

8 

9 

10def 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 

23def _get_type_hints(func: Callable[..., Any]): 

24 if sys.version_info >= (3, 9): 24 ↛ 27line 24 didn't jump to line 27 because the condition on line 24 was always true

25 hints = get_type_hints(func, include_extras=True) 

26 else: 

27 hints = get_type_hints(func) 

28 return hints 

29 

30 

31def 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 

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

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

53 return lambda x: x