Coverage for pydantic / errors.py: 100.00%

34 statements  

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

1"""Pydantic-specific errors.""" 

2 

3from __future__ import annotations as _annotations 1abcdefghijklsmnopqr

4 

5from typing import Any, ClassVar, Literal, Self 1abcdefghijklsmnopqr

6 

7from typing_inspection.introspection import Qualifier 1abcdefghijklsmnopqr

8 

9from pydantic._internal import _repr 1abcdefghijklsmnopqr

10 

11from .version import version_short 1abcdefghijklsmnopqr

12 

13__all__ = ( 1abcdefghijklsmnopqr

14 'PydanticUserError', 

15 'PydanticUndefinedAnnotation', 

16 'PydanticSchemaGenerationError', 

17 'PydanticInvalidForJsonSchema', 

18 'PydanticForbiddenQualifier', 

19 'PydanticErrorCodes', 

20) 

21 

22# We use this URL to allow for future flexibility about how we host the docs, while allowing for Pydantic 

23# code in the while with "old" URLs to still work. 

24# 'u' refers to "user errors" - e.g. errors caused by developers using pydantic, as opposed to validation errors. 

25DEV_ERROR_DOCS_URL = f'https://errors.pydantic.dev/{version_short()}/u/' 1abcdefghijklsmnopqr

26PydanticErrorCodes = Literal[ 1abcdefghijklsmnopqr

27 'class-not-fully-defined', 

28 'decorator-invalid-fields', 

29 'decorator-missing-arguments', 

30 'decorator-missing-field', 

31 'discriminator-no-field', 

32 'discriminator-alias-type', 

33 'discriminator-needs-literal', 

34 'discriminator-alias', 

35 'discriminator-validator', 

36 'callable-discriminator-no-tag', 

37 'typed-dict-version', 

38 'model-field-overridden', 

39 'model-field-missing-annotation', 

40 'circular-reference-schema', 

41 'invalid-for-json-schema', 

42 'json-schema-already-used', 

43 'base-model-instantiated', 

44 'undefined-annotation', 

45 'schema-for-unknown-type', 

46 'create-model-field-definitions', 

47 'create-model-namespace', 

48 'validator-instance-method', 

49 'model-after-validator-classmethod', 

50 'validator-input-type', 

51 'model-serializer-instance-method', 

52 'validator-signature', 

53 'field-serializer-signature', 

54 'model-serializer-signature', 

55 'multiple-field-serializers', 

56 'invalid-annotated-type', 

57 'type-adapter-config-unused', 

58 'root-model-extra', 

59 'unevaluable-type-annotation', 

60 'dataclass-init-false-extra-allow', 

61 'clashing-init-and-init-var', 

62 'model-config-invalid-field-name', 

63 'with-config-on-model', 

64 'dataclass-on-model', 

65 'validate-call-type', 

66 'unpack-typed-dict', 

67 'overlapping-unpack-typed-dict', 

68 'invalid-self-type', 

69 'validate-by-alias-and-name-false', 

70] 

71 

72 

73class PydanticErrorMixin: 1abcdefghijklsmnopqr

74 """A mixin class for common functionality shared by all Pydantic-specific errors. 

75 

76 Attributes: 

77 message: A message describing the error. 

78 code: An optional error code from PydanticErrorCodes enum. 

79 """ 

80 

81 def __init__(self, message: str, *, code: PydanticErrorCodes | None) -> None: 1abcdefghijklsmnopqr

82 self.message = message 1abcdefghijklsmnopqr

83 self.code = code 1abcdefghijklsmnopqr

84 

85 def __str__(self) -> str: 1abcdefghijklsmnopqr

86 if self.code is None: 1abcdefghijklmnopqr

87 return self.message 1abcdefghijklmnopqr

88 else: 

89 return f'{self.message}\n\nFor further information visit {DEV_ERROR_DOCS_URL}{self.code}' 1abcdefghijklmnopqr

90 

91 

92class PydanticUserError(PydanticErrorMixin, RuntimeError): 1abcdefghijklsmnopqr

93 """An error raised due to incorrect use of Pydantic.""" 

94 

95 

96class PydanticUndefinedAnnotation(PydanticErrorMixin, NameError): 1abcdefghijklsmnopqr

97 """A subclass of `NameError` raised when handling undefined annotations during `CoreSchema` generation. 

98 

99 Attributes: 

100 name: Name of the error, of `None` if not available. 

101 message: Description of the error. 

102 """ 

103 

104 def __init__(self, name: str | None, message: str) -> None: 1abcdefghijklsmnopqr

105 self.name = name 1abcdefghijklsmnopqr

106 super().__init__(message=message, code='undefined-annotation') 1abcdefghijklsmnopqr

107 

108 @classmethod 1abcdefghijklsmnopqr

109 def from_name_error(cls, name_error: NameError) -> Self: 1abcdefghijklsmnopqr

110 """Convert a `NameError` to a `PydanticUndefinedAnnotation` error. 

111 

112 Args: 

113 name_error: `NameError` to be converted. 

114 

115 Returns: 

116 Converted `PydanticUndefinedAnnotation` error. 

117 """ 

118 return cls(name=name_error.name, message=str(name_error)) 1abcdefghijklsmnopqr

119 

120 

121class PydanticSchemaGenerationError(PydanticUserError): 1abcdefghijklsmnopqr

122 """An error raised during failures to generate a `CoreSchema` for some type. 

123 

124 Attributes: 

125 message: Description of the error. 

126 """ 

127 

128 def __init__(self, message: str) -> None: 1abcdefghijklsmnopqr

129 super().__init__(message, code='schema-for-unknown-type') 1abcdefghijklmnopqr

130 

131 

132class PydanticInvalidForJsonSchema(PydanticUserError): 1abcdefghijklsmnopqr

133 """An error raised during failures to generate a JSON schema for some `CoreSchema`. 

134 

135 Attributes: 

136 message: Description of the error. 

137 """ 

138 

139 def __init__(self, message: str) -> None: 1abcdefghijklsmnopqr

140 super().__init__(message, code='invalid-for-json-schema') 1abcdefghijklmnopqr

141 

142 

143class PydanticForbiddenQualifier(PydanticUserError): 1abcdefghijklsmnopqr

144 """An error raised if a forbidden type qualifier is found in a type annotation.""" 

145 

146 _qualifier_repr_map: ClassVar[dict[Qualifier, str]] = { 1abcdefghijklsmnopqr

147 'required': 'typing.Required', 

148 'not_required': 'typing.NotRequired', 

149 'read_only': 'typing.ReadOnly', 

150 'class_var': 'typing.ClassVar', 

151 'init_var': 'dataclasses.InitVar', 

152 'final': 'typing.Final', 

153 } 

154 

155 def __init__(self, qualifier: Qualifier, annotation: Any) -> None: 1abcdefghijklsmnopqr

156 super().__init__( 1abcdefghijklmnopqr

157 message=( 

158 f'The annotation {_repr.display_as_type(annotation)!r} contains the {self._qualifier_repr_map[qualifier]!r} ' 

159 f'type qualifier, which is invalid in the context it is defined.' 

160 ), 

161 code=None, 

162 )