Coverage for pydantic / validate_call_decorator.py: 100.00%

42 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-21 11:56 +0000

1"""Decorator for validating function calls.""" 

2 

3from __future__ import annotations as _annotations 1gabhijkcdlmnoefpqr

4 

5import inspect 1gabhijkcdlmnoefpqr

6from collections.abc import Callable 1gabhijkcdlmnoefpqr

7from functools import partial 1gabhijkcdlmnoefpqr

8from types import BuiltinFunctionType 1gabhijkcdlmnoefpqr

9from typing import TYPE_CHECKING, Any, TypeVar, cast, overload 1gabhijkcdlmnoefpqr

10 

11from ._internal import _generate_schema, _typing_extra, _validate_call 1gabhijkcdlmnoefpqr

12from .errors import PydanticUserError 1gabhijkcdlmnoefpqr

13 

14__all__ = ('validate_call',) 1gabhijkcdlmnoefpqr

15 

16if TYPE_CHECKING: 1gabhijkcdlmnoefpqr

17 from .config import ConfigDict 

18 

19 AnyCallableT = TypeVar('AnyCallableT', bound=Callable[..., Any]) 

20 

21 

22_INVALID_TYPE_ERROR_CODE = 'validate-call-type' 1gabhijkcdlmnoefpqr

23 

24 

25def _check_function_type(function: object) -> None: 1gabhijkcdlmnoefpqr

26 """Check if the input function is a supported type for `validate_call`.""" 

27 if isinstance(function, _generate_schema.VALIDATE_CALL_SUPPORTED_TYPES): 1gabhijkcdlmnoefpqr

28 try: 1gabhijkcdlmnoefpqr

29 _typing_extra.signature_no_eval(cast(_generate_schema.ValidateCallSupportedTypes, function)) 1gabhijkcdlmnoefpqr

30 except (ValueError, TypeError): 1gabhijkcdlmnoefpqr

31 raise PydanticUserError( 1gabhijkcdlmnoefpqr

32 f"Input function `{function}` doesn't have a valid signature", code=_INVALID_TYPE_ERROR_CODE 

33 ) 

34 

35 if isinstance(function, partial): 1gabhijkcdlmnoefpqr

36 try: 1gabhijkcdlmnoefpqr

37 assert not isinstance(partial.func, partial), 'Partial of partial' 1gabhijkcdlmnoefpqr

38 _check_function_type(function.func) 1gabhijkcdlmnoefpqr

39 except PydanticUserError as e: 1gabhijkcdlmnoefpqr

40 raise PydanticUserError( 1gabhijkcdlmnoefpqr

41 f'Partial of `{function.func}` is invalid because the type of `{function.func}` is not supported by `validate_call`', 

42 code=_INVALID_TYPE_ERROR_CODE, 

43 ) from e 

44 

45 return 1gabhijkcdlmnoefpqr

46 

47 if isinstance(function, BuiltinFunctionType): 1gabhijkcdlmnoefpqr

48 raise PydanticUserError(f'Input built-in function `{function}` is not supported', code=_INVALID_TYPE_ERROR_CODE) 1gabhijkcdlmnoefpqr

49 if isinstance(function, (classmethod, staticmethod, property)): 1gabhijkcdlmnoefpqr

50 name = type(function).__name__ 1gabhijkcdlmnoefpqr

51 raise PydanticUserError( 1gabhijkcdlmnoefpqr

52 f'The `@{name}` decorator should be applied after `@validate_call` (put `@{name}` on top)', 

53 code=_INVALID_TYPE_ERROR_CODE, 

54 ) 

55 

56 if inspect.isclass(function): 1gabhijkcdlmnoefpqr

57 raise PydanticUserError( 1gabhijkcdlmnoefpqr

58 f'Unable to validate {function}: `validate_call` should be applied to functions, not classes (put `@validate_call` on top of `__init__` or `__new__` instead)', 

59 code=_INVALID_TYPE_ERROR_CODE, 

60 ) 

61 if callable(function): 1gabhijkcdlmnoefpqr

62 raise PydanticUserError( 1gabhijkcdlmnoefpqr

63 f'Unable to validate {function}: `validate_call` should be applied to functions, not instances or other callables. Use `validate_call` explicitly on `__call__` instead.', 

64 code=_INVALID_TYPE_ERROR_CODE, 

65 ) 

66 

67 raise PydanticUserError( 1gabhijkcdlmnoefpqr

68 f'Unable to validate {function}: `validate_call` should be applied to one of the following: function, method, partial, or lambda', 

69 code=_INVALID_TYPE_ERROR_CODE, 

70 ) 

71 

72 

73@overload 1gabhijkcdlmnoefpqr

74def validate_call( 1gabhijkcdlmnoefpqr

75 *, config: ConfigDict | None = None, validate_return: bool = False 1gabhijkcdlmnoefpqr

76) -> Callable[[AnyCallableT], AnyCallableT]: ... 1abcdef

77 

78 

79@overload 1gabhijkcdlmnoefpqr

80def validate_call(func: AnyCallableT, /) -> AnyCallableT: ... 1gabhijkcdlmnoefpqr

81 

82 

83def validate_call( 1gabhijkcdlmnoefpqr

84 func: AnyCallableT | None = None, 

85 /, 

86 *, 

87 config: ConfigDict | None = None, 

88 validate_return: bool = False, 

89) -> AnyCallableT | Callable[[AnyCallableT], AnyCallableT]: 

90 """!!! abstract "Usage Documentation" 

91 [Validation Decorator](../concepts/validation_decorator.md) 

92 

93 Returns a wrapper around the function that validates the arguments and, optionally, the return value. 

94 

95 Usage may be either as a plain decorator `@validate_call` or with arguments (`@validate_call(...)`). 

96 

97 When a decorated call fails, the [`ValidationError`][pydantic_core.ValidationError] reports the 

98 rejected argument and value. [Logfire](../integrations/logfire.md) can retain the complete call input 

99 and surrounding trace context — see [Troubleshooting validation errors](../errors/troubleshooting.md). 

100 

101 Args: 

102 func: The function to be wrapped. 

103 config: The configuration dictionary. 

104 validate_return: Whether to validate the return value. 

105 

106 Returns: 

107 The decorated function. 

108 """ 

109 parent_namespace = _typing_extra.parent_frame_namespace() 1gabhijkcdlmnoefpqr

110 

111 def validate(function: AnyCallableT) -> AnyCallableT: 1gabhijkcdlmnoefpqr

112 _check_function_type(function) 1gabhijkcdlmnoefpqr

113 validate_call_wrapper = _validate_call.ValidateCallWrapper( 1gabhijkcdlmnoefpqr

114 cast(_generate_schema.ValidateCallSupportedTypes, function), config, validate_return, parent_namespace 

115 ) 

116 return _validate_call.update_wrapper_attributes(function, validate_call_wrapper.__call__) # type: ignore 1gabhijkcdlmnoefpqr

117 

118 if func is not None: 1gabhijkcdlmnoefpqr

119 return validate(func) 1gabhijkcdlmnoefpqr

120 else: 

121 return validate 1gabhijkcdlmnoefpqr