pboot-validator 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pboot_validator/__init__.py +461 -0
- pboot_validator/_internal/__init__.py +0 -0
- pboot_validator/_internal/_config.py +408 -0
- pboot_validator/_internal/_contextlib.py +84 -0
- pboot_validator/_internal/_core_metadata.py +97 -0
- pboot_validator/_internal/_core_utils.py +156 -0
- pboot_validator/_internal/_dataclasses.py +327 -0
- pboot_validator/_internal/_decorators.py +906 -0
- pboot_validator/_internal/_decorators_v1.py +174 -0
- pboot_validator/_internal/_discriminated_union.py +510 -0
- pboot_validator/_internal/_docs_extraction.py +128 -0
- pboot_validator/_internal/_fields.py +910 -0
- pboot_validator/_internal/_forward_ref.py +23 -0
- pboot_validator/_internal/_generate_schema.py +3053 -0
- pboot_validator/_internal/_generics.py +572 -0
- pboot_validator/_internal/_git.py +27 -0
- pboot_validator/_internal/_import_utils.py +20 -0
- pboot_validator/_internal/_known_annotated_metadata.py +412 -0
- pboot_validator/_internal/_mock_val_ser.py +241 -0
- pboot_validator/_internal/_model_construction.py +833 -0
- pboot_validator/_internal/_namespace_utils.py +300 -0
- pboot_validator/_internal/_repr.py +129 -0
- pboot_validator/_internal/_schema_gather.py +49 -0
- pboot_validator/_internal/_schema_generation_shared.py +126 -0
- pboot_validator/_internal/_serializers.py +59 -0
- pboot_validator/_internal/_signature.py +193 -0
- pboot_validator/_internal/_type_refs.py +128 -0
- pboot_validator/_internal/_typing_extra.py +506 -0
- pboot_validator/_internal/_utils.py +433 -0
- pboot_validator/_internal/_validate_call.py +141 -0
- pboot_validator/_internal/_validators.py +541 -0
- pboot_validator/_migration.py +317 -0
- pboot_validator/alias_generators.py +62 -0
- pboot_validator/aliases.py +136 -0
- pboot_validator/annotated_handlers.py +123 -0
- pboot_validator/class_validators.py +5 -0
- pboot_validator/color.py +605 -0
- pboot_validator/config.py +1295 -0
- pboot_validator/dataclasses.py +385 -0
- pboot_validator/datetime_parse.py +5 -0
- pboot_validator/decorator.py +5 -0
- pboot_validator/deprecated/__init__.py +0 -0
- pboot_validator/deprecated/class_validators.py +257 -0
- pboot_validator/deprecated/config.py +72 -0
- pboot_validator/deprecated/copy_internals.py +224 -0
- pboot_validator/deprecated/decorator.py +286 -0
- pboot_validator/deprecated/json.py +142 -0
- pboot_validator/deprecated/parse.py +81 -0
- pboot_validator/deprecated/tools.py +104 -0
- pboot_validator/env_settings.py +5 -0
- pboot_validator/error_wrappers.py +5 -0
- pboot_validator/errors.py +185 -0
- pboot_validator/experimental/__init__.py +1 -0
- pboot_validator/experimental/arguments_schema.py +44 -0
- pboot_validator/experimental/missing_sentinel.py +29 -0
- pboot_validator/experimental/pipeline.py +684 -0
- pboot_validator/fields.py +2065 -0
- pboot_validator/functional_serializers.py +461 -0
- pboot_validator/functional_validators.py +920 -0
- pboot_validator/generics.py +5 -0
- pboot_validator/json.py +5 -0
- pboot_validator/json_schema.py +3283 -0
- pboot_validator/main.py +1947 -0
- pboot_validator/mypy.py +1469 -0
- pboot_validator/networks.py +1417 -0
- pboot_validator/parse.py +5 -0
- pboot_validator/plugin/__init__.py +190 -0
- pboot_validator/plugin/_loader.py +56 -0
- pboot_validator/plugin/_schema_validator.py +152 -0
- pboot_validator/py.typed +0 -0
- pboot_validator/root_model.py +189 -0
- pboot_validator/schema.py +5 -0
- pboot_validator/tools.py +5 -0
- pboot_validator/type_adapter.py +780 -0
- pboot_validator/types.py +3405 -0
- pboot_validator/typing.py +5 -0
- pboot_validator/utils.py +5 -0
- pboot_validator/v1/__init__.py +131 -0
- pboot_validator/v1/_hypothesis_plugin.py +391 -0
- pboot_validator/v1/annotated_types.py +72 -0
- pboot_validator/v1/class_validators.py +361 -0
- pboot_validator/v1/color.py +494 -0
- pboot_validator/v1/config.py +191 -0
- pboot_validator/v1/dataclasses.py +503 -0
- pboot_validator/v1/datetime_parse.py +248 -0
- pboot_validator/v1/decorator.py +264 -0
- pboot_validator/v1/env_settings.py +350 -0
- pboot_validator/v1/error_wrappers.py +161 -0
- pboot_validator/v1/errors.py +646 -0
- pboot_validator/v1/fields.py +1253 -0
- pboot_validator/v1/generics.py +400 -0
- pboot_validator/v1/json.py +112 -0
- pboot_validator/v1/main.py +1130 -0
- pboot_validator/v1/mypy.py +950 -0
- pboot_validator/v1/networks.py +747 -0
- pboot_validator/v1/parse.py +66 -0
- pboot_validator/v1/py.typed +0 -0
- pboot_validator/v1/schema.py +1163 -0
- pboot_validator/v1/tools.py +92 -0
- pboot_validator/v1/types.py +1213 -0
- pboot_validator/v1/typing.py +627 -0
- pboot_validator/v1/utils.py +807 -0
- pboot_validator/v1/validators.py +768 -0
- pboot_validator/v1/version.py +38 -0
- pboot_validator/validate_call_decorator.py +121 -0
- pboot_validator/validators.py +5 -0
- pboot_validator/version.py +113 -0
- pboot_validator/warnings.py +130 -0
- pboot_validator-1.0.0.dist-info/METADATA +93 -0
- pboot_validator-1.0.0.dist-info/RECORD +112 -0
- pboot_validator-1.0.0.dist-info/WHEEL +4 -0
- pboot_validator-1.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import datetime
|
|
2
|
+
import warnings
|
|
3
|
+
from collections import deque
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from decimal import Decimal
|
|
6
|
+
from enum import Enum
|
|
7
|
+
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from re import Pattern
|
|
10
|
+
from types import GeneratorType
|
|
11
|
+
from typing import TYPE_CHECKING, Any
|
|
12
|
+
from uuid import UUID
|
|
13
|
+
|
|
14
|
+
from typing_extensions import deprecated
|
|
15
|
+
|
|
16
|
+
from .._internal._import_utils import import_cached_base_model
|
|
17
|
+
from ..color import Color
|
|
18
|
+
from ..networks import NameEmail
|
|
19
|
+
from ..types import SecretBytes, SecretStr
|
|
20
|
+
from ..warnings import PydanticDeprecatedSince20
|
|
21
|
+
|
|
22
|
+
if not TYPE_CHECKING:
|
|
23
|
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
|
24
|
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
|
25
|
+
DeprecationWarning = PydanticDeprecatedSince20
|
|
26
|
+
|
|
27
|
+
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def isoformat(o: datetime.date | datetime.time) -> str:
|
|
31
|
+
return o.isoformat()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def decimal_encoder(dec_value: Decimal) -> int | float:
|
|
35
|
+
"""Encodes a Decimal as an int if there's no exponent, otherwise float.
|
|
36
|
+
|
|
37
|
+
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
|
|
38
|
+
where an integer (but not int typed) is used. Encoding this as a float
|
|
39
|
+
results in failed round-tripping between encode and parse.
|
|
40
|
+
Our Id type is a prime example of this.
|
|
41
|
+
|
|
42
|
+
>>> decimal_encoder(Decimal("1.0"))
|
|
43
|
+
1.0
|
|
44
|
+
|
|
45
|
+
>>> decimal_encoder(Decimal("1"))
|
|
46
|
+
1
|
|
47
|
+
"""
|
|
48
|
+
exponent = dec_value.as_tuple().exponent
|
|
49
|
+
if isinstance(exponent, int) and exponent >= 0:
|
|
50
|
+
return int(dec_value)
|
|
51
|
+
else:
|
|
52
|
+
return float(dec_value)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
ENCODERS_BY_TYPE: dict[type[Any], Callable[[Any], Any]] = {
|
|
56
|
+
bytes: lambda o: o.decode(),
|
|
57
|
+
Color: str,
|
|
58
|
+
datetime.date: isoformat,
|
|
59
|
+
datetime.datetime: isoformat,
|
|
60
|
+
datetime.time: isoformat,
|
|
61
|
+
datetime.timedelta: lambda td: td.total_seconds(),
|
|
62
|
+
Decimal: decimal_encoder,
|
|
63
|
+
Enum: lambda o: o.value,
|
|
64
|
+
frozenset: list,
|
|
65
|
+
deque: list,
|
|
66
|
+
GeneratorType: list,
|
|
67
|
+
IPv4Address: str,
|
|
68
|
+
IPv4Interface: str,
|
|
69
|
+
IPv4Network: str,
|
|
70
|
+
IPv6Address: str,
|
|
71
|
+
IPv6Interface: str,
|
|
72
|
+
IPv6Network: str,
|
|
73
|
+
NameEmail: str,
|
|
74
|
+
Path: str,
|
|
75
|
+
Pattern: lambda o: o.pattern,
|
|
76
|
+
SecretBytes: str,
|
|
77
|
+
SecretStr: str,
|
|
78
|
+
set: list,
|
|
79
|
+
UUID: str,
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@deprecated(
|
|
84
|
+
'`pydantic_encoder` is deprecated, use `pydantic_core.to_jsonable_python` instead.',
|
|
85
|
+
category=None,
|
|
86
|
+
)
|
|
87
|
+
def pydantic_encoder(obj: Any) -> Any:
|
|
88
|
+
warnings.warn(
|
|
89
|
+
'`pydantic_encoder` is deprecated, use `pydantic_core.to_jsonable_python` instead.',
|
|
90
|
+
category=PydanticDeprecatedSince20,
|
|
91
|
+
stacklevel=2,
|
|
92
|
+
)
|
|
93
|
+
from dataclasses import asdict, is_dataclass
|
|
94
|
+
|
|
95
|
+
BaseModel = import_cached_base_model()
|
|
96
|
+
|
|
97
|
+
if isinstance(obj, BaseModel):
|
|
98
|
+
return obj.model_dump()
|
|
99
|
+
elif is_dataclass(obj):
|
|
100
|
+
return asdict(obj) # type: ignore
|
|
101
|
+
|
|
102
|
+
# Check the class type and its superclasses for a matching encoder
|
|
103
|
+
for base in obj.__class__.__mro__[:-1]:
|
|
104
|
+
try:
|
|
105
|
+
encoder = ENCODERS_BY_TYPE[base]
|
|
106
|
+
except KeyError:
|
|
107
|
+
continue
|
|
108
|
+
return encoder(obj)
|
|
109
|
+
else: # We have exited the for loop without finding a suitable encoder
|
|
110
|
+
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
# TODO: Add a suggested migration path once there is a way to use custom encoders
|
|
114
|
+
@deprecated(
|
|
115
|
+
'`custom_pydantic_encoder` is deprecated, use `BaseModel.model_dump` instead.',
|
|
116
|
+
category=None,
|
|
117
|
+
)
|
|
118
|
+
def custom_pydantic_encoder(type_encoders: dict[Any, Callable[[type[Any]], Any]], obj: Any) -> Any:
|
|
119
|
+
warnings.warn(
|
|
120
|
+
'`custom_pydantic_encoder` is deprecated, use `BaseModel.model_dump` instead.',
|
|
121
|
+
category=PydanticDeprecatedSince20,
|
|
122
|
+
stacklevel=2,
|
|
123
|
+
)
|
|
124
|
+
# Check the class type and its superclasses for a matching encoder
|
|
125
|
+
for base in obj.__class__.__mro__[:-1]:
|
|
126
|
+
try:
|
|
127
|
+
encoder = type_encoders[base]
|
|
128
|
+
except KeyError:
|
|
129
|
+
continue
|
|
130
|
+
|
|
131
|
+
return encoder(obj)
|
|
132
|
+
else: # We have exited the for loop without finding a suitable encoder
|
|
133
|
+
return pydantic_encoder(obj)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@deprecated('`timedelta_isoformat` is deprecated.', category=None)
|
|
137
|
+
def timedelta_isoformat(td: datetime.timedelta) -> str:
|
|
138
|
+
"""ISO 8601 encoding for Python timedelta object."""
|
|
139
|
+
warnings.warn('`timedelta_isoformat` is deprecated.', category=PydanticDeprecatedSince20, stacklevel=2)
|
|
140
|
+
minutes, seconds = divmod(td.seconds, 60)
|
|
141
|
+
hours, minutes = divmod(minutes, 60)
|
|
142
|
+
return f'{"-" if td.days < 0 else ""}P{abs(td.days)}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import pickle
|
|
5
|
+
import warnings
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from enum import Enum
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import TYPE_CHECKING, Any
|
|
10
|
+
|
|
11
|
+
from typing_extensions import deprecated
|
|
12
|
+
|
|
13
|
+
from ..warnings import PydanticDeprecatedSince20
|
|
14
|
+
|
|
15
|
+
if not TYPE_CHECKING:
|
|
16
|
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
|
17
|
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
|
18
|
+
DeprecationWarning = PydanticDeprecatedSince20
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Protocol(str, Enum):
|
|
22
|
+
json = 'json'
|
|
23
|
+
pickle = 'pickle'
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@deprecated('`load_str_bytes` is deprecated.', category=None)
|
|
27
|
+
def load_str_bytes(
|
|
28
|
+
b: str | bytes,
|
|
29
|
+
*,
|
|
30
|
+
content_type: str | None = None,
|
|
31
|
+
encoding: str = 'utf8',
|
|
32
|
+
proto: Protocol | None = None,
|
|
33
|
+
allow_pickle: bool = False,
|
|
34
|
+
json_loads: Callable[[str], Any] = json.loads,
|
|
35
|
+
) -> Any:
|
|
36
|
+
warnings.warn('`load_str_bytes` is deprecated.', category=PydanticDeprecatedSince20, stacklevel=2)
|
|
37
|
+
if proto is None and content_type:
|
|
38
|
+
if content_type.endswith(('json', 'javascript')):
|
|
39
|
+
pass
|
|
40
|
+
elif allow_pickle and content_type.endswith('pickle'):
|
|
41
|
+
proto = Protocol.pickle
|
|
42
|
+
else:
|
|
43
|
+
raise TypeError(f'Unknown content-type: {content_type}')
|
|
44
|
+
|
|
45
|
+
proto = proto or Protocol.json
|
|
46
|
+
|
|
47
|
+
if proto == Protocol.json:
|
|
48
|
+
if isinstance(b, bytes):
|
|
49
|
+
b = b.decode(encoding)
|
|
50
|
+
return json_loads(b) # type: ignore
|
|
51
|
+
elif proto == Protocol.pickle:
|
|
52
|
+
if not allow_pickle:
|
|
53
|
+
raise RuntimeError('Trying to decode with pickle with allow_pickle=False')
|
|
54
|
+
bb = b if isinstance(b, bytes) else b.encode() # type: ignore
|
|
55
|
+
return pickle.loads(bb)
|
|
56
|
+
else:
|
|
57
|
+
raise TypeError(f'Unknown protocol: {proto}')
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@deprecated('`load_file` is deprecated.', category=None)
|
|
61
|
+
def load_file(
|
|
62
|
+
path: str | Path,
|
|
63
|
+
*,
|
|
64
|
+
content_type: str | None = None,
|
|
65
|
+
encoding: str = 'utf8',
|
|
66
|
+
proto: Protocol | None = None,
|
|
67
|
+
allow_pickle: bool = False,
|
|
68
|
+
json_loads: Callable[[str], Any] = json.loads,
|
|
69
|
+
) -> Any:
|
|
70
|
+
warnings.warn('`load_file` is deprecated.', category=PydanticDeprecatedSince20, stacklevel=2)
|
|
71
|
+
path = Path(path)
|
|
72
|
+
b = path.read_bytes()
|
|
73
|
+
if content_type is None:
|
|
74
|
+
if path.suffix in ('.js', '.json'):
|
|
75
|
+
proto = Protocol.json
|
|
76
|
+
elif path.suffix == '.pkl':
|
|
77
|
+
proto = Protocol.pickle
|
|
78
|
+
|
|
79
|
+
return load_str_bytes(
|
|
80
|
+
b, proto=proto, content_type=content_type, encoding=encoding, allow_pickle=allow_pickle, json_loads=json_loads
|
|
81
|
+
)
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import warnings
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from typing import TYPE_CHECKING, Any, TypeVar, Union
|
|
7
|
+
|
|
8
|
+
from typing_extensions import deprecated
|
|
9
|
+
|
|
10
|
+
from ..json_schema import DEFAULT_REF_TEMPLATE, GenerateJsonSchema
|
|
11
|
+
from ..type_adapter import TypeAdapter
|
|
12
|
+
from ..warnings import PydanticDeprecatedSince20
|
|
13
|
+
|
|
14
|
+
if not TYPE_CHECKING:
|
|
15
|
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
|
16
|
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
|
17
|
+
DeprecationWarning = PydanticDeprecatedSince20
|
|
18
|
+
|
|
19
|
+
__all__ = 'parse_obj_as', 'schema_of', 'schema_json_of'
|
|
20
|
+
|
|
21
|
+
NameFactory = Union[str, Callable[[type[Any]], str]]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
T = TypeVar('T')
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@deprecated(
|
|
28
|
+
'`parse_obj_as` is deprecated. Use `pboot_validator.TypeAdapter.validate_python` instead.',
|
|
29
|
+
category=None,
|
|
30
|
+
)
|
|
31
|
+
def parse_obj_as(type_: type[T], obj: Any, type_name: NameFactory | None = None) -> T:
|
|
32
|
+
warnings.warn(
|
|
33
|
+
'`parse_obj_as` is deprecated. Use `pboot_validator.TypeAdapter.validate_python` instead.',
|
|
34
|
+
category=PydanticDeprecatedSince20,
|
|
35
|
+
stacklevel=2,
|
|
36
|
+
)
|
|
37
|
+
if type_name is not None: # pragma: no cover
|
|
38
|
+
warnings.warn(
|
|
39
|
+
'The type_name parameter is deprecated. parse_obj_as no longer creates temporary models',
|
|
40
|
+
DeprecationWarning,
|
|
41
|
+
stacklevel=2,
|
|
42
|
+
)
|
|
43
|
+
return TypeAdapter(type_).validate_python(obj)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@deprecated(
|
|
47
|
+
'`schema_of` is deprecated. Use `pboot_validator.TypeAdapter.json_schema` instead.',
|
|
48
|
+
category=None,
|
|
49
|
+
)
|
|
50
|
+
def schema_of(
|
|
51
|
+
type_: Any,
|
|
52
|
+
*,
|
|
53
|
+
title: NameFactory | None = None,
|
|
54
|
+
by_alias: bool = True,
|
|
55
|
+
ref_template: str = DEFAULT_REF_TEMPLATE,
|
|
56
|
+
schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
|
|
57
|
+
) -> dict[str, Any]:
|
|
58
|
+
"""Generate a JSON schema (as dict) for the passed model or dynamically generated one."""
|
|
59
|
+
warnings.warn(
|
|
60
|
+
'`schema_of` is deprecated. Use `pboot_validator.TypeAdapter.json_schema` instead.',
|
|
61
|
+
category=PydanticDeprecatedSince20,
|
|
62
|
+
stacklevel=2,
|
|
63
|
+
)
|
|
64
|
+
res = TypeAdapter(type_).json_schema(
|
|
65
|
+
by_alias=by_alias,
|
|
66
|
+
schema_generator=schema_generator,
|
|
67
|
+
ref_template=ref_template,
|
|
68
|
+
)
|
|
69
|
+
if title is not None:
|
|
70
|
+
if isinstance(title, str):
|
|
71
|
+
res['title'] = title
|
|
72
|
+
else:
|
|
73
|
+
warnings.warn(
|
|
74
|
+
'Passing a callable for the `title` parameter is deprecated and no longer supported',
|
|
75
|
+
DeprecationWarning,
|
|
76
|
+
stacklevel=2,
|
|
77
|
+
)
|
|
78
|
+
res['title'] = title(type_)
|
|
79
|
+
return res
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@deprecated(
|
|
83
|
+
'`schema_json_of` is deprecated. Use `pboot_validator.TypeAdapter.json_schema` instead.',
|
|
84
|
+
category=None,
|
|
85
|
+
)
|
|
86
|
+
def schema_json_of(
|
|
87
|
+
type_: Any,
|
|
88
|
+
*,
|
|
89
|
+
title: NameFactory | None = None,
|
|
90
|
+
by_alias: bool = True,
|
|
91
|
+
ref_template: str = DEFAULT_REF_TEMPLATE,
|
|
92
|
+
schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
|
|
93
|
+
**dumps_kwargs: Any,
|
|
94
|
+
) -> str:
|
|
95
|
+
"""Generate a JSON schema (as JSON) for the passed model or dynamically generated one."""
|
|
96
|
+
warnings.warn(
|
|
97
|
+
'`schema_json_of` is deprecated. Use `pboot_validator.TypeAdapter.json_schema` instead.',
|
|
98
|
+
category=PydanticDeprecatedSince20,
|
|
99
|
+
stacklevel=2,
|
|
100
|
+
)
|
|
101
|
+
return json.dumps(
|
|
102
|
+
schema_of(type_, title=title, by_alias=by_alias, ref_template=ref_template, schema_generator=schema_generator),
|
|
103
|
+
**dumps_kwargs,
|
|
104
|
+
)
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Pydantic-specific errors."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations as _annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, ClassVar, Literal
|
|
6
|
+
|
|
7
|
+
from typing_extensions import Self
|
|
8
|
+
from typing_inspection.introspection import Qualifier
|
|
9
|
+
|
|
10
|
+
from pboot_validator._internal import _repr
|
|
11
|
+
|
|
12
|
+
from ._migration import getattr_migration
|
|
13
|
+
from .version import version_short
|
|
14
|
+
|
|
15
|
+
__all__ = (
|
|
16
|
+
'PydanticUserError',
|
|
17
|
+
'PydanticUndefinedAnnotation',
|
|
18
|
+
'PydanticImportError',
|
|
19
|
+
'PydanticSchemaGenerationError',
|
|
20
|
+
'PydanticInvalidForJsonSchema',
|
|
21
|
+
'PydanticForbiddenQualifier',
|
|
22
|
+
'PydanticErrorCodes',
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
# We use this URL to allow for future flexibility about how we host the docs, while allowing for Pydantic
|
|
26
|
+
# code in the while with "old" URLs to still work.
|
|
27
|
+
# 'u' refers to "user errors" - e.g. errors caused by developers using pydantic, as opposed to validation errors.
|
|
28
|
+
DEV_ERROR_DOCS_URL = f'https://errors.pydantic.dev/{version_short()}/u/'
|
|
29
|
+
PydanticErrorCodes = Literal[
|
|
30
|
+
'class-not-fully-defined',
|
|
31
|
+
'custom-json-schema',
|
|
32
|
+
'decorator-invalid-fields',
|
|
33
|
+
'decorator-missing-arguments',
|
|
34
|
+
'decorator-missing-field',
|
|
35
|
+
'discriminator-no-field',
|
|
36
|
+
'discriminator-alias-type',
|
|
37
|
+
'discriminator-needs-literal',
|
|
38
|
+
'discriminator-alias',
|
|
39
|
+
'discriminator-validator',
|
|
40
|
+
'callable-discriminator-no-tag',
|
|
41
|
+
'typed-dict-version',
|
|
42
|
+
'model-field-overridden',
|
|
43
|
+
'model-field-missing-annotation',
|
|
44
|
+
'config-both',
|
|
45
|
+
'removed-kwargs',
|
|
46
|
+
'circular-reference-schema',
|
|
47
|
+
'invalid-for-json-schema',
|
|
48
|
+
'json-schema-already-used',
|
|
49
|
+
'base-model-instantiated',
|
|
50
|
+
'undefined-annotation',
|
|
51
|
+
'schema-for-unknown-type',
|
|
52
|
+
'import-error',
|
|
53
|
+
'create-model-field-definitions',
|
|
54
|
+
'create-model-namespace',
|
|
55
|
+
'validator-instance-method',
|
|
56
|
+
'validator-input-type',
|
|
57
|
+
'root-validator-pre-skip',
|
|
58
|
+
'model-serializer-instance-method',
|
|
59
|
+
'validator-field-config-info',
|
|
60
|
+
'validator-v1-signature',
|
|
61
|
+
'validator-signature',
|
|
62
|
+
'field-serializer-signature',
|
|
63
|
+
'model-serializer-signature',
|
|
64
|
+
'multiple-field-serializers',
|
|
65
|
+
'invalid-annotated-type',
|
|
66
|
+
'type-adapter-config-unused',
|
|
67
|
+
'root-model-extra',
|
|
68
|
+
'unevaluable-type-annotation',
|
|
69
|
+
'dataclass-init-false-extra-allow',
|
|
70
|
+
'clashing-init-and-init-var',
|
|
71
|
+
'model-config-invalid-field-name',
|
|
72
|
+
'with-config-on-model',
|
|
73
|
+
'dataclass-on-model',
|
|
74
|
+
'validate-call-type',
|
|
75
|
+
'unpack-typed-dict',
|
|
76
|
+
'overlapping-unpack-typed-dict',
|
|
77
|
+
'invalid-self-type',
|
|
78
|
+
'validate-by-alias-and-name-false',
|
|
79
|
+
]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class PydanticErrorMixin:
|
|
83
|
+
"""A mixin class for common functionality shared by all Pydantic-specific errors.
|
|
84
|
+
|
|
85
|
+
Attributes:
|
|
86
|
+
message: A message describing the error.
|
|
87
|
+
code: An optional error code from PydanticErrorCodes enum.
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
def __init__(self, message: str, *, code: PydanticErrorCodes | None) -> None:
|
|
91
|
+
self.message = message
|
|
92
|
+
self.code = code
|
|
93
|
+
|
|
94
|
+
def __str__(self) -> str:
|
|
95
|
+
if self.code is None:
|
|
96
|
+
return self.message
|
|
97
|
+
else:
|
|
98
|
+
return f'{self.message}\n\nFor further information visit {DEV_ERROR_DOCS_URL}{self.code}'
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class PydanticUserError(PydanticErrorMixin, RuntimeError):
|
|
102
|
+
"""An error raised due to incorrect use of Pydantic."""
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class PydanticUndefinedAnnotation(PydanticErrorMixin, NameError):
|
|
106
|
+
"""A subclass of `NameError` raised when handling undefined annotations during `CoreSchema` generation.
|
|
107
|
+
|
|
108
|
+
Attributes:
|
|
109
|
+
name: Name of the error, of `None` if not available.
|
|
110
|
+
message: Description of the error.
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
def __init__(self, name: str | None, message: str) -> None:
|
|
114
|
+
self.name = name
|
|
115
|
+
super().__init__(message=message, code='undefined-annotation')
|
|
116
|
+
|
|
117
|
+
@classmethod
|
|
118
|
+
def from_name_error(cls, name_error: NameError) -> Self:
|
|
119
|
+
"""Convert a `NameError` to a `PydanticUndefinedAnnotation` error.
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
name_error: `NameError` to be converted.
|
|
123
|
+
|
|
124
|
+
Returns:
|
|
125
|
+
Converted `PydanticUndefinedAnnotation` error.
|
|
126
|
+
"""
|
|
127
|
+
return cls(name=name_error.name, message=str(name_error))
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class PydanticImportError(PydanticErrorMixin, ImportError):
|
|
131
|
+
"""An error raised when an import fails due to module changes between V1 and V2.
|
|
132
|
+
|
|
133
|
+
Attributes:
|
|
134
|
+
message: Description of the error.
|
|
135
|
+
"""
|
|
136
|
+
|
|
137
|
+
def __init__(self, message: str) -> None:
|
|
138
|
+
super().__init__(message, code='import-error')
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class PydanticSchemaGenerationError(PydanticUserError):
|
|
142
|
+
"""An error raised during failures to generate a `CoreSchema` for some type.
|
|
143
|
+
|
|
144
|
+
Attributes:
|
|
145
|
+
message: Description of the error.
|
|
146
|
+
"""
|
|
147
|
+
|
|
148
|
+
def __init__(self, message: str) -> None:
|
|
149
|
+
super().__init__(message, code='schema-for-unknown-type')
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class PydanticInvalidForJsonSchema(PydanticUserError):
|
|
153
|
+
"""An error raised during failures to generate a JSON schema for some `CoreSchema`.
|
|
154
|
+
|
|
155
|
+
Attributes:
|
|
156
|
+
message: Description of the error.
|
|
157
|
+
"""
|
|
158
|
+
|
|
159
|
+
def __init__(self, message: str) -> None:
|
|
160
|
+
super().__init__(message, code='invalid-for-json-schema')
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class PydanticForbiddenQualifier(PydanticUserError):
|
|
164
|
+
"""An error raised if a forbidden type qualifier is found in a type annotation."""
|
|
165
|
+
|
|
166
|
+
_qualifier_repr_map: ClassVar[dict[Qualifier, str]] = {
|
|
167
|
+
'required': 'typing.Required',
|
|
168
|
+
'not_required': 'typing.NotRequired',
|
|
169
|
+
'read_only': 'typing.ReadOnly',
|
|
170
|
+
'class_var': 'typing.ClassVar',
|
|
171
|
+
'init_var': 'dataclasses.InitVar',
|
|
172
|
+
'final': 'typing.Final',
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
def __init__(self, qualifier: Qualifier, annotation: Any) -> None:
|
|
176
|
+
super().__init__(
|
|
177
|
+
message=(
|
|
178
|
+
f'The annotation {_repr.display_as_type(annotation)!r} contains the {self._qualifier_repr_map[qualifier]!r} '
|
|
179
|
+
f'type qualifier, which is invalid in the context it is defined.'
|
|
180
|
+
),
|
|
181
|
+
code=None,
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
__getattr__ = getattr_migration(__name__)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""The "experimental" module of pydantic contains potential new features that are subject to change."""
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Experimental module exposing a function to generate a core schema that validates callable arguments."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from typing import Any, Literal
|
|
7
|
+
|
|
8
|
+
from pydantic_core import CoreSchema
|
|
9
|
+
|
|
10
|
+
from pboot_validator import ConfigDict
|
|
11
|
+
from pboot_validator._internal import _config, _generate_schema, _namespace_utils
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def generate_arguments_schema(
|
|
15
|
+
func: Callable[..., Any],
|
|
16
|
+
schema_type: Literal['arguments', 'arguments-v3'] = 'arguments-v3',
|
|
17
|
+
parameters_callback: Callable[[int, str, Any], Literal['skip'] | None] | None = None,
|
|
18
|
+
config: ConfigDict | None = None,
|
|
19
|
+
) -> CoreSchema:
|
|
20
|
+
"""Generate the schema for the arguments of a function.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
func: The function to generate the schema for.
|
|
24
|
+
schema_type: The type of schema to generate.
|
|
25
|
+
parameters_callback: A callable that will be invoked for each parameter. The callback
|
|
26
|
+
should take three required arguments: the index, the name and the type annotation
|
|
27
|
+
(or [`Parameter.empty`][inspect.Parameter.empty] if not annotated) of the parameter.
|
|
28
|
+
The callback can optionally return `'skip'`, so that the parameter gets excluded
|
|
29
|
+
from the resulting schema.
|
|
30
|
+
config: The configuration to use.
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
The generated schema.
|
|
34
|
+
"""
|
|
35
|
+
generate_schema = _generate_schema.GenerateSchema(
|
|
36
|
+
_config.ConfigWrapper(config),
|
|
37
|
+
ns_resolver=_namespace_utils.NsResolver(namespaces_tuple=_namespace_utils.ns_for_function(func)),
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
if schema_type == 'arguments':
|
|
41
|
+
schema = generate_schema._arguments_schema(func, parameters_callback) # pyright: ignore[reportArgumentType]
|
|
42
|
+
else:
|
|
43
|
+
schema = generate_schema._arguments_v3_schema(func, parameters_callback) # pyright: ignore[reportArgumentType]
|
|
44
|
+
return generate_schema.clean_schema(schema)
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Experimental module exposing the `MISSING` sentinel.
|
|
2
|
+
|
|
3
|
+
!!! warning "Deprecated"
|
|
4
|
+
The `MISSING` sentinel is no longer experimental, and should be imported from the main `pydantic` module.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import warnings
|
|
8
|
+
from typing import TYPE_CHECKING, Any
|
|
9
|
+
|
|
10
|
+
from ..warnings import PydanticDeprecatedSince214
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from pydantic_core import MISSING
|
|
14
|
+
|
|
15
|
+
__all__ = ('MISSING',)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def __getattr__(name: str) -> Any:
|
|
19
|
+
if name == 'MISSING':
|
|
20
|
+
warnings.warn(
|
|
21
|
+
'The `MISSING` sentinel is no longer experimental. Import it from the main `pydantic` module instead.',
|
|
22
|
+
category=PydanticDeprecatedSince214,
|
|
23
|
+
stacklevel=2,
|
|
24
|
+
)
|
|
25
|
+
from pydantic_core import MISSING
|
|
26
|
+
|
|
27
|
+
return MISSING
|
|
28
|
+
else: # pragma: no cover
|
|
29
|
+
raise AttributeError(f'module {__name__!r} has no attribute {name!r}')
|