Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- vllm/lib/python3.10/site-packages/pydantic/__init__.py +428 -0
- vllm/lib/python3.10/site-packages/pydantic/_migration.py +308 -0
- vllm/lib/python3.10/site-packages/pydantic/alias_generators.py +62 -0
- vllm/lib/python3.10/site-packages/pydantic/aliases.py +132 -0
- vllm/lib/python3.10/site-packages/pydantic/annotated_handlers.py +122 -0
- vllm/lib/python3.10/site-packages/pydantic/class_validators.py +5 -0
- vllm/lib/python3.10/site-packages/pydantic/color.py +604 -0
- vllm/lib/python3.10/site-packages/pydantic/config.py +1049 -0
- vllm/lib/python3.10/site-packages/pydantic/dataclasses.py +366 -0
- vllm/lib/python3.10/site-packages/pydantic/datetime_parse.py +5 -0
- vllm/lib/python3.10/site-packages/pydantic/decorator.py +5 -0
- vllm/lib/python3.10/site-packages/pydantic/deprecated/__init__.py +0 -0
- vllm/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/class_validators.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/config.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/copy_internals.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/decorator.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/json.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/parse.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/tools.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/pydantic/deprecated/class_validators.py +256 -0
- vllm/lib/python3.10/site-packages/pydantic/deprecated/config.py +72 -0
- vllm/lib/python3.10/site-packages/pydantic/deprecated/copy_internals.py +224 -0
- vllm/lib/python3.10/site-packages/pydantic/deprecated/decorator.py +283 -0
- vllm/lib/python3.10/site-packages/pydantic/deprecated/json.py +141 -0
- vllm/lib/python3.10/site-packages/pydantic/deprecated/parse.py +80 -0
- vllm/lib/python3.10/site-packages/pydantic/deprecated/tools.py +103 -0
- vllm/lib/python3.10/site-packages/pydantic/env_settings.py +5 -0
- vllm/lib/python3.10/site-packages/pydantic/error_wrappers.py +5 -0
- vllm/lib/python3.10/site-packages/pydantic/errors.py +162 -0
- vllm/lib/python3.10/site-packages/pydantic/experimental/__init__.py +10 -0
- vllm/lib/python3.10/site-packages/pydantic/experimental/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/pydantic/experimental/__pycache__/pipeline.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/pydantic/experimental/pipeline.py +669 -0
- vllm/lib/python3.10/site-packages/pydantic/fields.py +1504 -0
- vllm/lib/python3.10/site-packages/pydantic/functional_serializers.py +449 -0
- vllm/lib/python3.10/site-packages/pydantic/functional_validators.py +846 -0
- vllm/lib/python3.10/site-packages/pydantic/generics.py +5 -0
- vllm/lib/python3.10/site-packages/pydantic/json.py +5 -0
- vllm/lib/python3.10/site-packages/pydantic/json_schema.py +0 -0
- vllm/lib/python3.10/site-packages/pydantic/main.py +1689 -0
- vllm/lib/python3.10/site-packages/pydantic/networks.py +1243 -0
- vllm/lib/python3.10/site-packages/pydantic/py.typed +0 -0
- vllm/lib/python3.10/site-packages/pydantic/root_model.py +156 -0
- vllm/lib/python3.10/site-packages/pydantic/schema.py +5 -0
- vllm/lib/python3.10/site-packages/pydantic/tools.py +5 -0
- vllm/lib/python3.10/site-packages/pydantic/types.py +0 -0
- vllm/lib/python3.10/site-packages/pydantic/typing.py +5 -0
- vllm/lib/python3.10/site-packages/pydantic/utils.py +5 -0
- vllm/lib/python3.10/site-packages/pydantic/v1/__init__.py +131 -0
vllm/lib/python3.10/site-packages/pydantic/__init__.py
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import typing
|
| 2 |
+
from importlib import import_module
|
| 3 |
+
from warnings import warn
|
| 4 |
+
|
| 5 |
+
from ._migration import getattr_migration
|
| 6 |
+
from .version import VERSION
|
| 7 |
+
|
| 8 |
+
if typing.TYPE_CHECKING:
|
| 9 |
+
# import of virtually everything is supported via `__getattr__` below,
|
| 10 |
+
# but we need them here for type checking and IDE support
|
| 11 |
+
import pydantic_core
|
| 12 |
+
from pydantic_core.core_schema import (
|
| 13 |
+
FieldSerializationInfo,
|
| 14 |
+
SerializationInfo,
|
| 15 |
+
SerializerFunctionWrapHandler,
|
| 16 |
+
ValidationInfo,
|
| 17 |
+
ValidatorFunctionWrapHandler,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
from . import dataclasses
|
| 21 |
+
from .aliases import AliasChoices, AliasGenerator, AliasPath
|
| 22 |
+
from .annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler
|
| 23 |
+
from .config import ConfigDict, with_config
|
| 24 |
+
from .errors import *
|
| 25 |
+
from .fields import Field, PrivateAttr, computed_field
|
| 26 |
+
from .functional_serializers import (
|
| 27 |
+
PlainSerializer,
|
| 28 |
+
SerializeAsAny,
|
| 29 |
+
WrapSerializer,
|
| 30 |
+
field_serializer,
|
| 31 |
+
model_serializer,
|
| 32 |
+
)
|
| 33 |
+
from .functional_validators import (
|
| 34 |
+
AfterValidator,
|
| 35 |
+
BeforeValidator,
|
| 36 |
+
InstanceOf,
|
| 37 |
+
PlainValidator,
|
| 38 |
+
SkipValidation,
|
| 39 |
+
WrapValidator,
|
| 40 |
+
field_validator,
|
| 41 |
+
model_validator,
|
| 42 |
+
)
|
| 43 |
+
from .json_schema import WithJsonSchema
|
| 44 |
+
from .main import *
|
| 45 |
+
from .networks import *
|
| 46 |
+
from .type_adapter import TypeAdapter
|
| 47 |
+
from .types import *
|
| 48 |
+
from .validate_call_decorator import validate_call
|
| 49 |
+
from .warnings import (
|
| 50 |
+
PydanticDeprecatedSince20,
|
| 51 |
+
PydanticDeprecatedSince26,
|
| 52 |
+
PydanticDeprecatedSince29,
|
| 53 |
+
PydanticDeprecationWarning,
|
| 54 |
+
PydanticExperimentalWarning,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
# this encourages pycharm to import `ValidationError` from here, not pydantic_core
|
| 58 |
+
ValidationError = pydantic_core.ValidationError
|
| 59 |
+
from .deprecated.class_validators import root_validator, validator
|
| 60 |
+
from .deprecated.config import BaseConfig, Extra
|
| 61 |
+
from .deprecated.tools import *
|
| 62 |
+
from .root_model import RootModel
|
| 63 |
+
|
| 64 |
+
__version__ = VERSION
|
| 65 |
+
__all__ = (
|
| 66 |
+
# dataclasses
|
| 67 |
+
'dataclasses',
|
| 68 |
+
# functional validators
|
| 69 |
+
'field_validator',
|
| 70 |
+
'model_validator',
|
| 71 |
+
'AfterValidator',
|
| 72 |
+
'BeforeValidator',
|
| 73 |
+
'PlainValidator',
|
| 74 |
+
'WrapValidator',
|
| 75 |
+
'SkipValidation',
|
| 76 |
+
'InstanceOf',
|
| 77 |
+
# JSON Schema
|
| 78 |
+
'WithJsonSchema',
|
| 79 |
+
# deprecated V1 functional validators, these are imported via `__getattr__` below
|
| 80 |
+
'root_validator',
|
| 81 |
+
'validator',
|
| 82 |
+
# functional serializers
|
| 83 |
+
'field_serializer',
|
| 84 |
+
'model_serializer',
|
| 85 |
+
'PlainSerializer',
|
| 86 |
+
'SerializeAsAny',
|
| 87 |
+
'WrapSerializer',
|
| 88 |
+
# config
|
| 89 |
+
'ConfigDict',
|
| 90 |
+
'with_config',
|
| 91 |
+
# deprecated V1 config, these are imported via `__getattr__` below
|
| 92 |
+
'BaseConfig',
|
| 93 |
+
'Extra',
|
| 94 |
+
# validate_call
|
| 95 |
+
'validate_call',
|
| 96 |
+
# errors
|
| 97 |
+
'PydanticErrorCodes',
|
| 98 |
+
'PydanticUserError',
|
| 99 |
+
'PydanticSchemaGenerationError',
|
| 100 |
+
'PydanticImportError',
|
| 101 |
+
'PydanticUndefinedAnnotation',
|
| 102 |
+
'PydanticInvalidForJsonSchema',
|
| 103 |
+
# fields
|
| 104 |
+
'Field',
|
| 105 |
+
'computed_field',
|
| 106 |
+
'PrivateAttr',
|
| 107 |
+
# alias
|
| 108 |
+
'AliasChoices',
|
| 109 |
+
'AliasGenerator',
|
| 110 |
+
'AliasPath',
|
| 111 |
+
# main
|
| 112 |
+
'BaseModel',
|
| 113 |
+
'create_model',
|
| 114 |
+
# network
|
| 115 |
+
'AnyUrl',
|
| 116 |
+
'AnyHttpUrl',
|
| 117 |
+
'FileUrl',
|
| 118 |
+
'HttpUrl',
|
| 119 |
+
'FtpUrl',
|
| 120 |
+
'WebsocketUrl',
|
| 121 |
+
'AnyWebsocketUrl',
|
| 122 |
+
'UrlConstraints',
|
| 123 |
+
'EmailStr',
|
| 124 |
+
'NameEmail',
|
| 125 |
+
'IPvAnyAddress',
|
| 126 |
+
'IPvAnyInterface',
|
| 127 |
+
'IPvAnyNetwork',
|
| 128 |
+
'PostgresDsn',
|
| 129 |
+
'CockroachDsn',
|
| 130 |
+
'AmqpDsn',
|
| 131 |
+
'RedisDsn',
|
| 132 |
+
'MongoDsn',
|
| 133 |
+
'KafkaDsn',
|
| 134 |
+
'NatsDsn',
|
| 135 |
+
'MySQLDsn',
|
| 136 |
+
'MariaDBDsn',
|
| 137 |
+
'ClickHouseDsn',
|
| 138 |
+
'SnowflakeDsn',
|
| 139 |
+
'validate_email',
|
| 140 |
+
# root_model
|
| 141 |
+
'RootModel',
|
| 142 |
+
# deprecated tools, these are imported via `__getattr__` below
|
| 143 |
+
'parse_obj_as',
|
| 144 |
+
'schema_of',
|
| 145 |
+
'schema_json_of',
|
| 146 |
+
# types
|
| 147 |
+
'Strict',
|
| 148 |
+
'StrictStr',
|
| 149 |
+
'conbytes',
|
| 150 |
+
'conlist',
|
| 151 |
+
'conset',
|
| 152 |
+
'confrozenset',
|
| 153 |
+
'constr',
|
| 154 |
+
'StringConstraints',
|
| 155 |
+
'ImportString',
|
| 156 |
+
'conint',
|
| 157 |
+
'PositiveInt',
|
| 158 |
+
'NegativeInt',
|
| 159 |
+
'NonNegativeInt',
|
| 160 |
+
'NonPositiveInt',
|
| 161 |
+
'confloat',
|
| 162 |
+
'PositiveFloat',
|
| 163 |
+
'NegativeFloat',
|
| 164 |
+
'NonNegativeFloat',
|
| 165 |
+
'NonPositiveFloat',
|
| 166 |
+
'FiniteFloat',
|
| 167 |
+
'condecimal',
|
| 168 |
+
'condate',
|
| 169 |
+
'UUID1',
|
| 170 |
+
'UUID3',
|
| 171 |
+
'UUID4',
|
| 172 |
+
'UUID5',
|
| 173 |
+
'FilePath',
|
| 174 |
+
'DirectoryPath',
|
| 175 |
+
'NewPath',
|
| 176 |
+
'Json',
|
| 177 |
+
'Secret',
|
| 178 |
+
'SecretStr',
|
| 179 |
+
'SecretBytes',
|
| 180 |
+
'SocketPath',
|
| 181 |
+
'StrictBool',
|
| 182 |
+
'StrictBytes',
|
| 183 |
+
'StrictInt',
|
| 184 |
+
'StrictFloat',
|
| 185 |
+
'PaymentCardNumber',
|
| 186 |
+
'ByteSize',
|
| 187 |
+
'PastDate',
|
| 188 |
+
'FutureDate',
|
| 189 |
+
'PastDatetime',
|
| 190 |
+
'FutureDatetime',
|
| 191 |
+
'AwareDatetime',
|
| 192 |
+
'NaiveDatetime',
|
| 193 |
+
'AllowInfNan',
|
| 194 |
+
'EncoderProtocol',
|
| 195 |
+
'EncodedBytes',
|
| 196 |
+
'EncodedStr',
|
| 197 |
+
'Base64Encoder',
|
| 198 |
+
'Base64Bytes',
|
| 199 |
+
'Base64Str',
|
| 200 |
+
'Base64UrlBytes',
|
| 201 |
+
'Base64UrlStr',
|
| 202 |
+
'GetPydanticSchema',
|
| 203 |
+
'Tag',
|
| 204 |
+
'Discriminator',
|
| 205 |
+
'JsonValue',
|
| 206 |
+
'FailFast',
|
| 207 |
+
# type_adapter
|
| 208 |
+
'TypeAdapter',
|
| 209 |
+
# version
|
| 210 |
+
'__version__',
|
| 211 |
+
'VERSION',
|
| 212 |
+
# warnings
|
| 213 |
+
'PydanticDeprecatedSince20',
|
| 214 |
+
'PydanticDeprecatedSince26',
|
| 215 |
+
'PydanticDeprecatedSince29',
|
| 216 |
+
'PydanticDeprecationWarning',
|
| 217 |
+
'PydanticExperimentalWarning',
|
| 218 |
+
# annotated handlers
|
| 219 |
+
'GetCoreSchemaHandler',
|
| 220 |
+
'GetJsonSchemaHandler',
|
| 221 |
+
# pydantic_core
|
| 222 |
+
'ValidationError',
|
| 223 |
+
'ValidationInfo',
|
| 224 |
+
'SerializationInfo',
|
| 225 |
+
'ValidatorFunctionWrapHandler',
|
| 226 |
+
'FieldSerializationInfo',
|
| 227 |
+
'SerializerFunctionWrapHandler',
|
| 228 |
+
'OnErrorOmit',
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
# A mapping of {<member name>: (package, <module name>)} defining dynamic imports
|
| 232 |
+
_dynamic_imports: 'dict[str, tuple[str, str]]' = {
|
| 233 |
+
'dataclasses': (__spec__.parent, '__module__'),
|
| 234 |
+
# functional validators
|
| 235 |
+
'field_validator': (__spec__.parent, '.functional_validators'),
|
| 236 |
+
'model_validator': (__spec__.parent, '.functional_validators'),
|
| 237 |
+
'AfterValidator': (__spec__.parent, '.functional_validators'),
|
| 238 |
+
'BeforeValidator': (__spec__.parent, '.functional_validators'),
|
| 239 |
+
'PlainValidator': (__spec__.parent, '.functional_validators'),
|
| 240 |
+
'WrapValidator': (__spec__.parent, '.functional_validators'),
|
| 241 |
+
'SkipValidation': (__spec__.parent, '.functional_validators'),
|
| 242 |
+
'InstanceOf': (__spec__.parent, '.functional_validators'),
|
| 243 |
+
# JSON Schema
|
| 244 |
+
'WithJsonSchema': (__spec__.parent, '.json_schema'),
|
| 245 |
+
# functional serializers
|
| 246 |
+
'field_serializer': (__spec__.parent, '.functional_serializers'),
|
| 247 |
+
'model_serializer': (__spec__.parent, '.functional_serializers'),
|
| 248 |
+
'PlainSerializer': (__spec__.parent, '.functional_serializers'),
|
| 249 |
+
'SerializeAsAny': (__spec__.parent, '.functional_serializers'),
|
| 250 |
+
'WrapSerializer': (__spec__.parent, '.functional_serializers'),
|
| 251 |
+
# config
|
| 252 |
+
'ConfigDict': (__spec__.parent, '.config'),
|
| 253 |
+
'with_config': (__spec__.parent, '.config'),
|
| 254 |
+
# validate call
|
| 255 |
+
'validate_call': (__spec__.parent, '.validate_call_decorator'),
|
| 256 |
+
# errors
|
| 257 |
+
'PydanticErrorCodes': (__spec__.parent, '.errors'),
|
| 258 |
+
'PydanticUserError': (__spec__.parent, '.errors'),
|
| 259 |
+
'PydanticSchemaGenerationError': (__spec__.parent, '.errors'),
|
| 260 |
+
'PydanticImportError': (__spec__.parent, '.errors'),
|
| 261 |
+
'PydanticUndefinedAnnotation': (__spec__.parent, '.errors'),
|
| 262 |
+
'PydanticInvalidForJsonSchema': (__spec__.parent, '.errors'),
|
| 263 |
+
# fields
|
| 264 |
+
'Field': (__spec__.parent, '.fields'),
|
| 265 |
+
'computed_field': (__spec__.parent, '.fields'),
|
| 266 |
+
'PrivateAttr': (__spec__.parent, '.fields'),
|
| 267 |
+
# alias
|
| 268 |
+
'AliasChoices': (__spec__.parent, '.aliases'),
|
| 269 |
+
'AliasGenerator': (__spec__.parent, '.aliases'),
|
| 270 |
+
'AliasPath': (__spec__.parent, '.aliases'),
|
| 271 |
+
# main
|
| 272 |
+
'BaseModel': (__spec__.parent, '.main'),
|
| 273 |
+
'create_model': (__spec__.parent, '.main'),
|
| 274 |
+
# network
|
| 275 |
+
'AnyUrl': (__spec__.parent, '.networks'),
|
| 276 |
+
'AnyHttpUrl': (__spec__.parent, '.networks'),
|
| 277 |
+
'FileUrl': (__spec__.parent, '.networks'),
|
| 278 |
+
'HttpUrl': (__spec__.parent, '.networks'),
|
| 279 |
+
'FtpUrl': (__spec__.parent, '.networks'),
|
| 280 |
+
'WebsocketUrl': (__spec__.parent, '.networks'),
|
| 281 |
+
'AnyWebsocketUrl': (__spec__.parent, '.networks'),
|
| 282 |
+
'UrlConstraints': (__spec__.parent, '.networks'),
|
| 283 |
+
'EmailStr': (__spec__.parent, '.networks'),
|
| 284 |
+
'NameEmail': (__spec__.parent, '.networks'),
|
| 285 |
+
'IPvAnyAddress': (__spec__.parent, '.networks'),
|
| 286 |
+
'IPvAnyInterface': (__spec__.parent, '.networks'),
|
| 287 |
+
'IPvAnyNetwork': (__spec__.parent, '.networks'),
|
| 288 |
+
'PostgresDsn': (__spec__.parent, '.networks'),
|
| 289 |
+
'CockroachDsn': (__spec__.parent, '.networks'),
|
| 290 |
+
'AmqpDsn': (__spec__.parent, '.networks'),
|
| 291 |
+
'RedisDsn': (__spec__.parent, '.networks'),
|
| 292 |
+
'MongoDsn': (__spec__.parent, '.networks'),
|
| 293 |
+
'KafkaDsn': (__spec__.parent, '.networks'),
|
| 294 |
+
'NatsDsn': (__spec__.parent, '.networks'),
|
| 295 |
+
'MySQLDsn': (__spec__.parent, '.networks'),
|
| 296 |
+
'MariaDBDsn': (__spec__.parent, '.networks'),
|
| 297 |
+
'ClickHouseDsn': (__spec__.parent, '.networks'),
|
| 298 |
+
'SnowflakeDsn': (__spec__.parent, '.networks'),
|
| 299 |
+
'validate_email': (__spec__.parent, '.networks'),
|
| 300 |
+
# root_model
|
| 301 |
+
'RootModel': (__spec__.parent, '.root_model'),
|
| 302 |
+
# types
|
| 303 |
+
'Strict': (__spec__.parent, '.types'),
|
| 304 |
+
'StrictStr': (__spec__.parent, '.types'),
|
| 305 |
+
'conbytes': (__spec__.parent, '.types'),
|
| 306 |
+
'conlist': (__spec__.parent, '.types'),
|
| 307 |
+
'conset': (__spec__.parent, '.types'),
|
| 308 |
+
'confrozenset': (__spec__.parent, '.types'),
|
| 309 |
+
'constr': (__spec__.parent, '.types'),
|
| 310 |
+
'StringConstraints': (__spec__.parent, '.types'),
|
| 311 |
+
'ImportString': (__spec__.parent, '.types'),
|
| 312 |
+
'conint': (__spec__.parent, '.types'),
|
| 313 |
+
'PositiveInt': (__spec__.parent, '.types'),
|
| 314 |
+
'NegativeInt': (__spec__.parent, '.types'),
|
| 315 |
+
'NonNegativeInt': (__spec__.parent, '.types'),
|
| 316 |
+
'NonPositiveInt': (__spec__.parent, '.types'),
|
| 317 |
+
'confloat': (__spec__.parent, '.types'),
|
| 318 |
+
'PositiveFloat': (__spec__.parent, '.types'),
|
| 319 |
+
'NegativeFloat': (__spec__.parent, '.types'),
|
| 320 |
+
'NonNegativeFloat': (__spec__.parent, '.types'),
|
| 321 |
+
'NonPositiveFloat': (__spec__.parent, '.types'),
|
| 322 |
+
'FiniteFloat': (__spec__.parent, '.types'),
|
| 323 |
+
'condecimal': (__spec__.parent, '.types'),
|
| 324 |
+
'condate': (__spec__.parent, '.types'),
|
| 325 |
+
'UUID1': (__spec__.parent, '.types'),
|
| 326 |
+
'UUID3': (__spec__.parent, '.types'),
|
| 327 |
+
'UUID4': (__spec__.parent, '.types'),
|
| 328 |
+
'UUID5': (__spec__.parent, '.types'),
|
| 329 |
+
'FilePath': (__spec__.parent, '.types'),
|
| 330 |
+
'DirectoryPath': (__spec__.parent, '.types'),
|
| 331 |
+
'NewPath': (__spec__.parent, '.types'),
|
| 332 |
+
'Json': (__spec__.parent, '.types'),
|
| 333 |
+
'Secret': (__spec__.parent, '.types'),
|
| 334 |
+
'SecretStr': (__spec__.parent, '.types'),
|
| 335 |
+
'SecretBytes': (__spec__.parent, '.types'),
|
| 336 |
+
'StrictBool': (__spec__.parent, '.types'),
|
| 337 |
+
'StrictBytes': (__spec__.parent, '.types'),
|
| 338 |
+
'StrictInt': (__spec__.parent, '.types'),
|
| 339 |
+
'StrictFloat': (__spec__.parent, '.types'),
|
| 340 |
+
'PaymentCardNumber': (__spec__.parent, '.types'),
|
| 341 |
+
'ByteSize': (__spec__.parent, '.types'),
|
| 342 |
+
'PastDate': (__spec__.parent, '.types'),
|
| 343 |
+
'SocketPath': (__spec__.parent, '.types'),
|
| 344 |
+
'FutureDate': (__spec__.parent, '.types'),
|
| 345 |
+
'PastDatetime': (__spec__.parent, '.types'),
|
| 346 |
+
'FutureDatetime': (__spec__.parent, '.types'),
|
| 347 |
+
'AwareDatetime': (__spec__.parent, '.types'),
|
| 348 |
+
'NaiveDatetime': (__spec__.parent, '.types'),
|
| 349 |
+
'AllowInfNan': (__spec__.parent, '.types'),
|
| 350 |
+
'EncoderProtocol': (__spec__.parent, '.types'),
|
| 351 |
+
'EncodedBytes': (__spec__.parent, '.types'),
|
| 352 |
+
'EncodedStr': (__spec__.parent, '.types'),
|
| 353 |
+
'Base64Encoder': (__spec__.parent, '.types'),
|
| 354 |
+
'Base64Bytes': (__spec__.parent, '.types'),
|
| 355 |
+
'Base64Str': (__spec__.parent, '.types'),
|
| 356 |
+
'Base64UrlBytes': (__spec__.parent, '.types'),
|
| 357 |
+
'Base64UrlStr': (__spec__.parent, '.types'),
|
| 358 |
+
'GetPydanticSchema': (__spec__.parent, '.types'),
|
| 359 |
+
'Tag': (__spec__.parent, '.types'),
|
| 360 |
+
'Discriminator': (__spec__.parent, '.types'),
|
| 361 |
+
'JsonValue': (__spec__.parent, '.types'),
|
| 362 |
+
'OnErrorOmit': (__spec__.parent, '.types'),
|
| 363 |
+
'FailFast': (__spec__.parent, '.types'),
|
| 364 |
+
# type_adapter
|
| 365 |
+
'TypeAdapter': (__spec__.parent, '.type_adapter'),
|
| 366 |
+
# warnings
|
| 367 |
+
'PydanticDeprecatedSince20': (__spec__.parent, '.warnings'),
|
| 368 |
+
'PydanticDeprecatedSince26': (__spec__.parent, '.warnings'),
|
| 369 |
+
'PydanticDeprecatedSince29': (__spec__.parent, '.warnings'),
|
| 370 |
+
'PydanticDeprecationWarning': (__spec__.parent, '.warnings'),
|
| 371 |
+
'PydanticExperimentalWarning': (__spec__.parent, '.warnings'),
|
| 372 |
+
# annotated handlers
|
| 373 |
+
'GetCoreSchemaHandler': (__spec__.parent, '.annotated_handlers'),
|
| 374 |
+
'GetJsonSchemaHandler': (__spec__.parent, '.annotated_handlers'),
|
| 375 |
+
# pydantic_core stuff
|
| 376 |
+
'ValidationError': ('pydantic_core', '.'),
|
| 377 |
+
'ValidationInfo': ('pydantic_core', '.core_schema'),
|
| 378 |
+
'SerializationInfo': ('pydantic_core', '.core_schema'),
|
| 379 |
+
'ValidatorFunctionWrapHandler': ('pydantic_core', '.core_schema'),
|
| 380 |
+
'FieldSerializationInfo': ('pydantic_core', '.core_schema'),
|
| 381 |
+
'SerializerFunctionWrapHandler': ('pydantic_core', '.core_schema'),
|
| 382 |
+
# deprecated, mostly not included in __all__
|
| 383 |
+
'root_validator': (__spec__.parent, '.deprecated.class_validators'),
|
| 384 |
+
'validator': (__spec__.parent, '.deprecated.class_validators'),
|
| 385 |
+
'BaseConfig': (__spec__.parent, '.deprecated.config'),
|
| 386 |
+
'Extra': (__spec__.parent, '.deprecated.config'),
|
| 387 |
+
'parse_obj_as': (__spec__.parent, '.deprecated.tools'),
|
| 388 |
+
'schema_of': (__spec__.parent, '.deprecated.tools'),
|
| 389 |
+
'schema_json_of': (__spec__.parent, '.deprecated.tools'),
|
| 390 |
+
# deprecated dynamic imports
|
| 391 |
+
'FieldValidationInfo': ('pydantic_core', '.core_schema'),
|
| 392 |
+
'GenerateSchema': (__spec__.parent, '._internal._generate_schema'),
|
| 393 |
+
}
|
| 394 |
+
_deprecated_dynamic_imports = {'FieldValidationInfo', 'GenerateSchema'}
|
| 395 |
+
|
| 396 |
+
_getattr_migration = getattr_migration(__name__)
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def __getattr__(attr_name: str) -> object:
|
| 400 |
+
if attr_name in _deprecated_dynamic_imports:
|
| 401 |
+
warn(
|
| 402 |
+
f'Importing {attr_name} from `pydantic` is deprecated. This feature is either no longer supported, or is not public.',
|
| 403 |
+
DeprecationWarning,
|
| 404 |
+
stacklevel=2,
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
dynamic_attr = _dynamic_imports.get(attr_name)
|
| 408 |
+
if dynamic_attr is None:
|
| 409 |
+
return _getattr_migration(attr_name)
|
| 410 |
+
|
| 411 |
+
package, module_name = dynamic_attr
|
| 412 |
+
|
| 413 |
+
if module_name == '__module__':
|
| 414 |
+
result = import_module(f'.{attr_name}', package=package)
|
| 415 |
+
globals()[attr_name] = result
|
| 416 |
+
return result
|
| 417 |
+
else:
|
| 418 |
+
module = import_module(module_name, package=package)
|
| 419 |
+
result = getattr(module, attr_name)
|
| 420 |
+
g = globals()
|
| 421 |
+
for k, (_, v_module_name) in _dynamic_imports.items():
|
| 422 |
+
if v_module_name == module_name and k not in _deprecated_dynamic_imports:
|
| 423 |
+
g[k] = getattr(module, k)
|
| 424 |
+
return result
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def __dir__() -> 'list[str]':
|
| 428 |
+
return list(__all__)
|
vllm/lib/python3.10/site-packages/pydantic/_migration.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from typing import Any, Callable, Dict
|
| 3 |
+
|
| 4 |
+
from .version import version_short
|
| 5 |
+
|
| 6 |
+
MOVED_IN_V2 = {
|
| 7 |
+
'pydantic.utils:version_info': 'pydantic.version:version_info',
|
| 8 |
+
'pydantic.error_wrappers:ValidationError': 'pydantic:ValidationError',
|
| 9 |
+
'pydantic.utils:to_camel': 'pydantic.alias_generators:to_pascal',
|
| 10 |
+
'pydantic.utils:to_lower_camel': 'pydantic.alias_generators:to_camel',
|
| 11 |
+
'pydantic:PyObject': 'pydantic.types:ImportString',
|
| 12 |
+
'pydantic.types:PyObject': 'pydantic.types:ImportString',
|
| 13 |
+
'pydantic.generics:GenericModel': 'pydantic.BaseModel',
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
DEPRECATED_MOVED_IN_V2 = {
|
| 17 |
+
'pydantic.tools:schema_of': 'pydantic.deprecated.tools:schema_of',
|
| 18 |
+
'pydantic.tools:parse_obj_as': 'pydantic.deprecated.tools:parse_obj_as',
|
| 19 |
+
'pydantic.tools:schema_json_of': 'pydantic.deprecated.tools:schema_json_of',
|
| 20 |
+
'pydantic.json:pydantic_encoder': 'pydantic.deprecated.json:pydantic_encoder',
|
| 21 |
+
'pydantic:validate_arguments': 'pydantic.deprecated.decorator:validate_arguments',
|
| 22 |
+
'pydantic.json:custom_pydantic_encoder': 'pydantic.deprecated.json:custom_pydantic_encoder',
|
| 23 |
+
'pydantic.json:timedelta_isoformat': 'pydantic.deprecated.json:timedelta_isoformat',
|
| 24 |
+
'pydantic.decorator:validate_arguments': 'pydantic.deprecated.decorator:validate_arguments',
|
| 25 |
+
'pydantic.class_validators:validator': 'pydantic.deprecated.class_validators:validator',
|
| 26 |
+
'pydantic.class_validators:root_validator': 'pydantic.deprecated.class_validators:root_validator',
|
| 27 |
+
'pydantic.config:BaseConfig': 'pydantic.deprecated.config:BaseConfig',
|
| 28 |
+
'pydantic.config:Extra': 'pydantic.deprecated.config:Extra',
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
REDIRECT_TO_V1 = {
|
| 32 |
+
f'pydantic.utils:{obj}': f'pydantic.v1.utils:{obj}'
|
| 33 |
+
for obj in (
|
| 34 |
+
'deep_update',
|
| 35 |
+
'GetterDict',
|
| 36 |
+
'lenient_issubclass',
|
| 37 |
+
'lenient_isinstance',
|
| 38 |
+
'is_valid_field',
|
| 39 |
+
'update_not_none',
|
| 40 |
+
'import_string',
|
| 41 |
+
'Representation',
|
| 42 |
+
'ROOT_KEY',
|
| 43 |
+
'smart_deepcopy',
|
| 44 |
+
'sequence_like',
|
| 45 |
+
)
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
REMOVED_IN_V2 = {
|
| 50 |
+
'pydantic:ConstrainedBytes',
|
| 51 |
+
'pydantic:ConstrainedDate',
|
| 52 |
+
'pydantic:ConstrainedDecimal',
|
| 53 |
+
'pydantic:ConstrainedFloat',
|
| 54 |
+
'pydantic:ConstrainedFrozenSet',
|
| 55 |
+
'pydantic:ConstrainedInt',
|
| 56 |
+
'pydantic:ConstrainedList',
|
| 57 |
+
'pydantic:ConstrainedSet',
|
| 58 |
+
'pydantic:ConstrainedStr',
|
| 59 |
+
'pydantic:JsonWrapper',
|
| 60 |
+
'pydantic:NoneBytes',
|
| 61 |
+
'pydantic:NoneStr',
|
| 62 |
+
'pydantic:NoneStrBytes',
|
| 63 |
+
'pydantic:Protocol',
|
| 64 |
+
'pydantic:Required',
|
| 65 |
+
'pydantic:StrBytes',
|
| 66 |
+
'pydantic:compiled',
|
| 67 |
+
'pydantic.config:get_config',
|
| 68 |
+
'pydantic.config:inherit_config',
|
| 69 |
+
'pydantic.config:prepare_config',
|
| 70 |
+
'pydantic:create_model_from_namedtuple',
|
| 71 |
+
'pydantic:create_model_from_typeddict',
|
| 72 |
+
'pydantic.dataclasses:create_pydantic_model_from_dataclass',
|
| 73 |
+
'pydantic.dataclasses:make_dataclass_validator',
|
| 74 |
+
'pydantic.dataclasses:set_validation',
|
| 75 |
+
'pydantic.datetime_parse:parse_date',
|
| 76 |
+
'pydantic.datetime_parse:parse_time',
|
| 77 |
+
'pydantic.datetime_parse:parse_datetime',
|
| 78 |
+
'pydantic.datetime_parse:parse_duration',
|
| 79 |
+
'pydantic.error_wrappers:ErrorWrapper',
|
| 80 |
+
'pydantic.errors:AnyStrMaxLengthError',
|
| 81 |
+
'pydantic.errors:AnyStrMinLengthError',
|
| 82 |
+
'pydantic.errors:ArbitraryTypeError',
|
| 83 |
+
'pydantic.errors:BoolError',
|
| 84 |
+
'pydantic.errors:BytesError',
|
| 85 |
+
'pydantic.errors:CallableError',
|
| 86 |
+
'pydantic.errors:ClassError',
|
| 87 |
+
'pydantic.errors:ColorError',
|
| 88 |
+
'pydantic.errors:ConfigError',
|
| 89 |
+
'pydantic.errors:DataclassTypeError',
|
| 90 |
+
'pydantic.errors:DateError',
|
| 91 |
+
'pydantic.errors:DateNotInTheFutureError',
|
| 92 |
+
'pydantic.errors:DateNotInThePastError',
|
| 93 |
+
'pydantic.errors:DateTimeError',
|
| 94 |
+
'pydantic.errors:DecimalError',
|
| 95 |
+
'pydantic.errors:DecimalIsNotFiniteError',
|
| 96 |
+
'pydantic.errors:DecimalMaxDigitsError',
|
| 97 |
+
'pydantic.errors:DecimalMaxPlacesError',
|
| 98 |
+
'pydantic.errors:DecimalWholeDigitsError',
|
| 99 |
+
'pydantic.errors:DictError',
|
| 100 |
+
'pydantic.errors:DurationError',
|
| 101 |
+
'pydantic.errors:EmailError',
|
| 102 |
+
'pydantic.errors:EnumError',
|
| 103 |
+
'pydantic.errors:EnumMemberError',
|
| 104 |
+
'pydantic.errors:ExtraError',
|
| 105 |
+
'pydantic.errors:FloatError',
|
| 106 |
+
'pydantic.errors:FrozenSetError',
|
| 107 |
+
'pydantic.errors:FrozenSetMaxLengthError',
|
| 108 |
+
'pydantic.errors:FrozenSetMinLengthError',
|
| 109 |
+
'pydantic.errors:HashableError',
|
| 110 |
+
'pydantic.errors:IPv4AddressError',
|
| 111 |
+
'pydantic.errors:IPv4InterfaceError',
|
| 112 |
+
'pydantic.errors:IPv4NetworkError',
|
| 113 |
+
'pydantic.errors:IPv6AddressError',
|
| 114 |
+
'pydantic.errors:IPv6InterfaceError',
|
| 115 |
+
'pydantic.errors:IPv6NetworkError',
|
| 116 |
+
'pydantic.errors:IPvAnyAddressError',
|
| 117 |
+
'pydantic.errors:IPvAnyInterfaceError',
|
| 118 |
+
'pydantic.errors:IPvAnyNetworkError',
|
| 119 |
+
'pydantic.errors:IntEnumError',
|
| 120 |
+
'pydantic.errors:IntegerError',
|
| 121 |
+
'pydantic.errors:InvalidByteSize',
|
| 122 |
+
'pydantic.errors:InvalidByteSizeUnit',
|
| 123 |
+
'pydantic.errors:InvalidDiscriminator',
|
| 124 |
+
'pydantic.errors:InvalidLengthForBrand',
|
| 125 |
+
'pydantic.errors:JsonError',
|
| 126 |
+
'pydantic.errors:JsonTypeError',
|
| 127 |
+
'pydantic.errors:ListError',
|
| 128 |
+
'pydantic.errors:ListMaxLengthError',
|
| 129 |
+
'pydantic.errors:ListMinLengthError',
|
| 130 |
+
'pydantic.errors:ListUniqueItemsError',
|
| 131 |
+
'pydantic.errors:LuhnValidationError',
|
| 132 |
+
'pydantic.errors:MissingDiscriminator',
|
| 133 |
+
'pydantic.errors:MissingError',
|
| 134 |
+
'pydantic.errors:NoneIsAllowedError',
|
| 135 |
+
'pydantic.errors:NoneIsNotAllowedError',
|
| 136 |
+
'pydantic.errors:NotDigitError',
|
| 137 |
+
'pydantic.errors:NotNoneError',
|
| 138 |
+
'pydantic.errors:NumberNotGeError',
|
| 139 |
+
'pydantic.errors:NumberNotGtError',
|
| 140 |
+
'pydantic.errors:NumberNotLeError',
|
| 141 |
+
'pydantic.errors:NumberNotLtError',
|
| 142 |
+
'pydantic.errors:NumberNotMultipleError',
|
| 143 |
+
'pydantic.errors:PathError',
|
| 144 |
+
'pydantic.errors:PathNotADirectoryError',
|
| 145 |
+
'pydantic.errors:PathNotAFileError',
|
| 146 |
+
'pydantic.errors:PathNotExistsError',
|
| 147 |
+
'pydantic.errors:PatternError',
|
| 148 |
+
'pydantic.errors:PyObjectError',
|
| 149 |
+
'pydantic.errors:PydanticTypeError',
|
| 150 |
+
'pydantic.errors:PydanticValueError',
|
| 151 |
+
'pydantic.errors:SequenceError',
|
| 152 |
+
'pydantic.errors:SetError',
|
| 153 |
+
'pydantic.errors:SetMaxLengthError',
|
| 154 |
+
'pydantic.errors:SetMinLengthError',
|
| 155 |
+
'pydantic.errors:StrError',
|
| 156 |
+
'pydantic.errors:StrRegexError',
|
| 157 |
+
'pydantic.errors:StrictBoolError',
|
| 158 |
+
'pydantic.errors:SubclassError',
|
| 159 |
+
'pydantic.errors:TimeError',
|
| 160 |
+
'pydantic.errors:TupleError',
|
| 161 |
+
'pydantic.errors:TupleLengthError',
|
| 162 |
+
'pydantic.errors:UUIDError',
|
| 163 |
+
'pydantic.errors:UUIDVersionError',
|
| 164 |
+
'pydantic.errors:UrlError',
|
| 165 |
+
'pydantic.errors:UrlExtraError',
|
| 166 |
+
'pydantic.errors:UrlHostError',
|
| 167 |
+
'pydantic.errors:UrlHostTldError',
|
| 168 |
+
'pydantic.errors:UrlPortError',
|
| 169 |
+
'pydantic.errors:UrlSchemeError',
|
| 170 |
+
'pydantic.errors:UrlSchemePermittedError',
|
| 171 |
+
'pydantic.errors:UrlUserInfoError',
|
| 172 |
+
'pydantic.errors:WrongConstantError',
|
| 173 |
+
'pydantic.main:validate_model',
|
| 174 |
+
'pydantic.networks:stricturl',
|
| 175 |
+
'pydantic:parse_file_as',
|
| 176 |
+
'pydantic:parse_raw_as',
|
| 177 |
+
'pydantic:stricturl',
|
| 178 |
+
'pydantic.tools:parse_file_as',
|
| 179 |
+
'pydantic.tools:parse_raw_as',
|
| 180 |
+
'pydantic.types:ConstrainedBytes',
|
| 181 |
+
'pydantic.types:ConstrainedDate',
|
| 182 |
+
'pydantic.types:ConstrainedDecimal',
|
| 183 |
+
'pydantic.types:ConstrainedFloat',
|
| 184 |
+
'pydantic.types:ConstrainedFrozenSet',
|
| 185 |
+
'pydantic.types:ConstrainedInt',
|
| 186 |
+
'pydantic.types:ConstrainedList',
|
| 187 |
+
'pydantic.types:ConstrainedSet',
|
| 188 |
+
'pydantic.types:ConstrainedStr',
|
| 189 |
+
'pydantic.types:JsonWrapper',
|
| 190 |
+
'pydantic.types:NoneBytes',
|
| 191 |
+
'pydantic.types:NoneStr',
|
| 192 |
+
'pydantic.types:NoneStrBytes',
|
| 193 |
+
'pydantic.types:StrBytes',
|
| 194 |
+
'pydantic.typing:evaluate_forwardref',
|
| 195 |
+
'pydantic.typing:AbstractSetIntStr',
|
| 196 |
+
'pydantic.typing:AnyCallable',
|
| 197 |
+
'pydantic.typing:AnyClassMethod',
|
| 198 |
+
'pydantic.typing:CallableGenerator',
|
| 199 |
+
'pydantic.typing:DictAny',
|
| 200 |
+
'pydantic.typing:DictIntStrAny',
|
| 201 |
+
'pydantic.typing:DictStrAny',
|
| 202 |
+
'pydantic.typing:IntStr',
|
| 203 |
+
'pydantic.typing:ListStr',
|
| 204 |
+
'pydantic.typing:MappingIntStrAny',
|
| 205 |
+
'pydantic.typing:NoArgAnyCallable',
|
| 206 |
+
'pydantic.typing:NoneType',
|
| 207 |
+
'pydantic.typing:ReprArgs',
|
| 208 |
+
'pydantic.typing:SetStr',
|
| 209 |
+
'pydantic.typing:StrPath',
|
| 210 |
+
'pydantic.typing:TupleGenerator',
|
| 211 |
+
'pydantic.typing:WithArgsTypes',
|
| 212 |
+
'pydantic.typing:all_literal_values',
|
| 213 |
+
'pydantic.typing:display_as_type',
|
| 214 |
+
'pydantic.typing:get_all_type_hints',
|
| 215 |
+
'pydantic.typing:get_args',
|
| 216 |
+
'pydantic.typing:get_origin',
|
| 217 |
+
'pydantic.typing:get_sub_types',
|
| 218 |
+
'pydantic.typing:is_callable_type',
|
| 219 |
+
'pydantic.typing:is_classvar',
|
| 220 |
+
'pydantic.typing:is_finalvar',
|
| 221 |
+
'pydantic.typing:is_literal_type',
|
| 222 |
+
'pydantic.typing:is_namedtuple',
|
| 223 |
+
'pydantic.typing:is_new_type',
|
| 224 |
+
'pydantic.typing:is_none_type',
|
| 225 |
+
'pydantic.typing:is_typeddict',
|
| 226 |
+
'pydantic.typing:is_typeddict_special',
|
| 227 |
+
'pydantic.typing:is_union',
|
| 228 |
+
'pydantic.typing:new_type_supertype',
|
| 229 |
+
'pydantic.typing:resolve_annotations',
|
| 230 |
+
'pydantic.typing:typing_base',
|
| 231 |
+
'pydantic.typing:update_field_forward_refs',
|
| 232 |
+
'pydantic.typing:update_model_forward_refs',
|
| 233 |
+
'pydantic.utils:ClassAttribute',
|
| 234 |
+
'pydantic.utils:DUNDER_ATTRIBUTES',
|
| 235 |
+
'pydantic.utils:PyObjectStr',
|
| 236 |
+
'pydantic.utils:ValueItems',
|
| 237 |
+
'pydantic.utils:almost_equal_floats',
|
| 238 |
+
'pydantic.utils:get_discriminator_alias_and_values',
|
| 239 |
+
'pydantic.utils:get_model',
|
| 240 |
+
'pydantic.utils:get_unique_discriminator_alias',
|
| 241 |
+
'pydantic.utils:in_ipython',
|
| 242 |
+
'pydantic.utils:is_valid_identifier',
|
| 243 |
+
'pydantic.utils:path_type',
|
| 244 |
+
'pydantic.utils:validate_field_name',
|
| 245 |
+
'pydantic:validate_model',
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def getattr_migration(module: str) -> Callable[[str], Any]:
|
| 250 |
+
"""Implement PEP 562 for objects that were either moved or removed on the migration
|
| 251 |
+
to V2.
|
| 252 |
+
|
| 253 |
+
Args:
|
| 254 |
+
module: The module name.
|
| 255 |
+
|
| 256 |
+
Returns:
|
| 257 |
+
A callable that will raise an error if the object is not found.
|
| 258 |
+
"""
|
| 259 |
+
# This avoids circular import with errors.py.
|
| 260 |
+
from .errors import PydanticImportError
|
| 261 |
+
|
| 262 |
+
def wrapper(name: str) -> object:
|
| 263 |
+
"""Raise an error if the object is not found, or warn if it was moved.
|
| 264 |
+
|
| 265 |
+
In case it was moved, it still returns the object.
|
| 266 |
+
|
| 267 |
+
Args:
|
| 268 |
+
name: The object name.
|
| 269 |
+
|
| 270 |
+
Returns:
|
| 271 |
+
The object.
|
| 272 |
+
"""
|
| 273 |
+
if name == '__path__':
|
| 274 |
+
raise AttributeError(f'module {module!r} has no attribute {name!r}')
|
| 275 |
+
|
| 276 |
+
import warnings
|
| 277 |
+
|
| 278 |
+
from ._internal._validators import import_string
|
| 279 |
+
|
| 280 |
+
import_path = f'{module}:{name}'
|
| 281 |
+
if import_path in MOVED_IN_V2.keys():
|
| 282 |
+
new_location = MOVED_IN_V2[import_path]
|
| 283 |
+
warnings.warn(f'`{import_path}` has been moved to `{new_location}`.')
|
| 284 |
+
return import_string(MOVED_IN_V2[import_path])
|
| 285 |
+
if import_path in DEPRECATED_MOVED_IN_V2:
|
| 286 |
+
# skip the warning here because a deprecation warning will be raised elsewhere
|
| 287 |
+
return import_string(DEPRECATED_MOVED_IN_V2[import_path])
|
| 288 |
+
if import_path in REDIRECT_TO_V1:
|
| 289 |
+
new_location = REDIRECT_TO_V1[import_path]
|
| 290 |
+
warnings.warn(
|
| 291 |
+
f'`{import_path}` has been removed. We are importing from `{new_location}` instead.'
|
| 292 |
+
'See the migration guide for more details: https://docs.pydantic.dev/latest/migration/'
|
| 293 |
+
)
|
| 294 |
+
return import_string(REDIRECT_TO_V1[import_path])
|
| 295 |
+
if import_path == 'pydantic:BaseSettings':
|
| 296 |
+
raise PydanticImportError(
|
| 297 |
+
'`BaseSettings` has been moved to the `pydantic-settings` package. '
|
| 298 |
+
f'See https://docs.pydantic.dev/{version_short()}/migration/#basesettings-has-moved-to-pydantic-settings '
|
| 299 |
+
'for more details.'
|
| 300 |
+
)
|
| 301 |
+
if import_path in REMOVED_IN_V2:
|
| 302 |
+
raise PydanticImportError(f'`{import_path}` has been removed in V2.')
|
| 303 |
+
globals: Dict[str, Any] = sys.modules[module].__dict__
|
| 304 |
+
if name in globals:
|
| 305 |
+
return globals[name]
|
| 306 |
+
raise AttributeError(f'module {module!r} has no attribute {name!r}')
|
| 307 |
+
|
| 308 |
+
return wrapper
|
vllm/lib/python3.10/site-packages/pydantic/alias_generators.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Alias generators for converting between different capitalization conventions."""
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
__all__ = ('to_pascal', 'to_camel', 'to_snake')
|
| 6 |
+
|
| 7 |
+
# TODO: in V3, change the argument names to be more descriptive
|
| 8 |
+
# Generally, don't only convert from snake_case, or name the functions
|
| 9 |
+
# more specifically like snake_to_camel.
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def to_pascal(snake: str) -> str:
|
| 13 |
+
"""Convert a snake_case string to PascalCase.
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
snake: The string to convert.
|
| 17 |
+
|
| 18 |
+
Returns:
|
| 19 |
+
The PascalCase string.
|
| 20 |
+
"""
|
| 21 |
+
camel = snake.title()
|
| 22 |
+
return re.sub('([0-9A-Za-z])_(?=[0-9A-Z])', lambda m: m.group(1), camel)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def to_camel(snake: str) -> str:
|
| 26 |
+
"""Convert a snake_case string to camelCase.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
snake: The string to convert.
|
| 30 |
+
|
| 31 |
+
Returns:
|
| 32 |
+
The converted camelCase string.
|
| 33 |
+
"""
|
| 34 |
+
# If the string is already in camelCase and does not contain a digit followed
|
| 35 |
+
# by a lowercase letter, return it as it is
|
| 36 |
+
if re.match('^[a-z]+[A-Za-z0-9]*$', snake) and not re.search(r'\d[a-z]', snake):
|
| 37 |
+
return snake
|
| 38 |
+
|
| 39 |
+
camel = to_pascal(snake)
|
| 40 |
+
return re.sub('(^_*[A-Z])', lambda m: m.group(1).lower(), camel)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def to_snake(camel: str) -> str:
|
| 44 |
+
"""Convert a PascalCase, camelCase, or kebab-case string to snake_case.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
camel: The string to convert.
|
| 48 |
+
|
| 49 |
+
Returns:
|
| 50 |
+
The converted string in snake_case.
|
| 51 |
+
"""
|
| 52 |
+
# Handle the sequence of uppercase letters followed by a lowercase letter
|
| 53 |
+
snake = re.sub(r'([A-Z]+)([A-Z][a-z])', lambda m: f'{m.group(1)}_{m.group(2)}', camel)
|
| 54 |
+
# Insert an underscore between a lowercase letter and an uppercase letter
|
| 55 |
+
snake = re.sub(r'([a-z])([A-Z])', lambda m: f'{m.group(1)}_{m.group(2)}', snake)
|
| 56 |
+
# Insert an underscore between a digit and an uppercase letter
|
| 57 |
+
snake = re.sub(r'([0-9])([A-Z])', lambda m: f'{m.group(1)}_{m.group(2)}', snake)
|
| 58 |
+
# Insert an underscore between a lowercase letter and a digit
|
| 59 |
+
snake = re.sub(r'([a-z])([0-9])', lambda m: f'{m.group(1)}_{m.group(2)}', snake)
|
| 60 |
+
# Replace hyphens with underscores to handle kebab-case
|
| 61 |
+
snake = snake.replace('-', '_')
|
| 62 |
+
return snake.lower()
|
vllm/lib/python3.10/site-packages/pydantic/aliases.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Support for alias configurations."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import dataclasses
|
| 6 |
+
from typing import Any, Callable, Literal
|
| 7 |
+
|
| 8 |
+
from pydantic_core import PydanticUndefined
|
| 9 |
+
|
| 10 |
+
from ._internal import _internal_dataclass
|
| 11 |
+
|
| 12 |
+
__all__ = ('AliasGenerator', 'AliasPath', 'AliasChoices')
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@dataclasses.dataclass(**_internal_dataclass.slots_true)
|
| 16 |
+
class AliasPath:
|
| 17 |
+
"""Usage docs: https://docs.pydantic.dev/2.10/concepts/alias#aliaspath-and-aliaschoices
|
| 18 |
+
|
| 19 |
+
A data class used by `validation_alias` as a convenience to create aliases.
|
| 20 |
+
|
| 21 |
+
Attributes:
|
| 22 |
+
path: A list of string or integer aliases.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
path: list[int | str]
|
| 26 |
+
|
| 27 |
+
def __init__(self, first_arg: str, *args: str | int) -> None:
|
| 28 |
+
self.path = [first_arg] + list(args)
|
| 29 |
+
|
| 30 |
+
def convert_to_aliases(self) -> list[str | int]:
|
| 31 |
+
"""Converts arguments to a list of string or integer aliases.
|
| 32 |
+
|
| 33 |
+
Returns:
|
| 34 |
+
The list of aliases.
|
| 35 |
+
"""
|
| 36 |
+
return self.path
|
| 37 |
+
|
| 38 |
+
def search_dict_for_path(self, d: dict) -> Any:
|
| 39 |
+
"""Searches a dictionary for the path specified by the alias.
|
| 40 |
+
|
| 41 |
+
Returns:
|
| 42 |
+
The value at the specified path, or `PydanticUndefined` if the path is not found.
|
| 43 |
+
"""
|
| 44 |
+
v = d
|
| 45 |
+
for k in self.path:
|
| 46 |
+
if isinstance(v, str):
|
| 47 |
+
# disallow indexing into a str, like for AliasPath('x', 0) and x='abc'
|
| 48 |
+
return PydanticUndefined
|
| 49 |
+
try:
|
| 50 |
+
v = v[k]
|
| 51 |
+
except (KeyError, IndexError, TypeError):
|
| 52 |
+
return PydanticUndefined
|
| 53 |
+
return v
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@dataclasses.dataclass(**_internal_dataclass.slots_true)
|
| 57 |
+
class AliasChoices:
|
| 58 |
+
"""Usage docs: https://docs.pydantic.dev/2.10/concepts/alias#aliaspath-and-aliaschoices
|
| 59 |
+
|
| 60 |
+
A data class used by `validation_alias` as a convenience to create aliases.
|
| 61 |
+
|
| 62 |
+
Attributes:
|
| 63 |
+
choices: A list containing a string or `AliasPath`.
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
choices: list[str | AliasPath]
|
| 67 |
+
|
| 68 |
+
def __init__(self, first_choice: str | AliasPath, *choices: str | AliasPath) -> None:
|
| 69 |
+
self.choices = [first_choice] + list(choices)
|
| 70 |
+
|
| 71 |
+
def convert_to_aliases(self) -> list[list[str | int]]:
|
| 72 |
+
"""Converts arguments to a list of lists containing string or integer aliases.
|
| 73 |
+
|
| 74 |
+
Returns:
|
| 75 |
+
The list of aliases.
|
| 76 |
+
"""
|
| 77 |
+
aliases: list[list[str | int]] = []
|
| 78 |
+
for c in self.choices:
|
| 79 |
+
if isinstance(c, AliasPath):
|
| 80 |
+
aliases.append(c.convert_to_aliases())
|
| 81 |
+
else:
|
| 82 |
+
aliases.append([c])
|
| 83 |
+
return aliases
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@dataclasses.dataclass(**_internal_dataclass.slots_true)
|
| 87 |
+
class AliasGenerator:
|
| 88 |
+
"""Usage docs: https://docs.pydantic.dev/2.10/concepts/alias#using-an-aliasgenerator
|
| 89 |
+
|
| 90 |
+
A data class used by `alias_generator` as a convenience to create various aliases.
|
| 91 |
+
|
| 92 |
+
Attributes:
|
| 93 |
+
alias: A callable that takes a field name and returns an alias for it.
|
| 94 |
+
validation_alias: A callable that takes a field name and returns a validation alias for it.
|
| 95 |
+
serialization_alias: A callable that takes a field name and returns a serialization alias for it.
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
alias: Callable[[str], str] | None = None
|
| 99 |
+
validation_alias: Callable[[str], str | AliasPath | AliasChoices] | None = None
|
| 100 |
+
serialization_alias: Callable[[str], str] | None = None
|
| 101 |
+
|
| 102 |
+
def _generate_alias(
|
| 103 |
+
self,
|
| 104 |
+
alias_kind: Literal['alias', 'validation_alias', 'serialization_alias'],
|
| 105 |
+
allowed_types: tuple[type[str] | type[AliasPath] | type[AliasChoices], ...],
|
| 106 |
+
field_name: str,
|
| 107 |
+
) -> str | AliasPath | AliasChoices | None:
|
| 108 |
+
"""Generate an alias of the specified kind. Returns None if the alias generator is None.
|
| 109 |
+
|
| 110 |
+
Raises:
|
| 111 |
+
TypeError: If the alias generator produces an invalid type.
|
| 112 |
+
"""
|
| 113 |
+
alias = None
|
| 114 |
+
if alias_generator := getattr(self, alias_kind):
|
| 115 |
+
alias = alias_generator(field_name)
|
| 116 |
+
if alias and not isinstance(alias, allowed_types):
|
| 117 |
+
raise TypeError(
|
| 118 |
+
f'Invalid `{alias_kind}` type. `{alias_kind}` generator must produce one of `{allowed_types}`'
|
| 119 |
+
)
|
| 120 |
+
return alias
|
| 121 |
+
|
| 122 |
+
def generate_aliases(self, field_name: str) -> tuple[str | None, str | AliasPath | AliasChoices | None, str | None]:
|
| 123 |
+
"""Generate `alias`, `validation_alias`, and `serialization_alias` for a field.
|
| 124 |
+
|
| 125 |
+
Returns:
|
| 126 |
+
A tuple of three aliases - validation, alias, and serialization.
|
| 127 |
+
"""
|
| 128 |
+
alias = self._generate_alias('alias', (str,), field_name)
|
| 129 |
+
validation_alias = self._generate_alias('validation_alias', (str, AliasChoices, AliasPath), field_name)
|
| 130 |
+
serialization_alias = self._generate_alias('serialization_alias', (str,), field_name)
|
| 131 |
+
|
| 132 |
+
return alias, validation_alias, serialization_alias # type: ignore
|
vllm/lib/python3.10/site-packages/pydantic/annotated_handlers.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Type annotations to use with `__get_pydantic_core_schema__` and `__get_pydantic_json_schema__`."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations as _annotations
|
| 4 |
+
|
| 5 |
+
from typing import TYPE_CHECKING, Any, Union
|
| 6 |
+
|
| 7 |
+
from pydantic_core import core_schema
|
| 8 |
+
|
| 9 |
+
if TYPE_CHECKING:
|
| 10 |
+
from ._internal._namespace_utils import NamespacesTuple
|
| 11 |
+
from .json_schema import JsonSchemaMode, JsonSchemaValue
|
| 12 |
+
|
| 13 |
+
CoreSchemaOrField = Union[
|
| 14 |
+
core_schema.CoreSchema,
|
| 15 |
+
core_schema.ModelField,
|
| 16 |
+
core_schema.DataclassField,
|
| 17 |
+
core_schema.TypedDictField,
|
| 18 |
+
core_schema.ComputedField,
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
__all__ = 'GetJsonSchemaHandler', 'GetCoreSchemaHandler'
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class GetJsonSchemaHandler:
|
| 25 |
+
"""Handler to call into the next JSON schema generation function.
|
| 26 |
+
|
| 27 |
+
Attributes:
|
| 28 |
+
mode: Json schema mode, can be `validation` or `serialization`.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
mode: JsonSchemaMode
|
| 32 |
+
|
| 33 |
+
def __call__(self, core_schema: CoreSchemaOrField, /) -> JsonSchemaValue:
|
| 34 |
+
"""Call the inner handler and get the JsonSchemaValue it returns.
|
| 35 |
+
This will call the next JSON schema modifying function up until it calls
|
| 36 |
+
into `pydantic.json_schema.GenerateJsonSchema`, which will raise a
|
| 37 |
+
`pydantic.errors.PydanticInvalidForJsonSchema` error if it cannot generate
|
| 38 |
+
a JSON schema.
|
| 39 |
+
|
| 40 |
+
Args:
|
| 41 |
+
core_schema: A `pydantic_core.core_schema.CoreSchema`.
|
| 42 |
+
|
| 43 |
+
Returns:
|
| 44 |
+
JsonSchemaValue: The JSON schema generated by the inner JSON schema modify
|
| 45 |
+
functions.
|
| 46 |
+
"""
|
| 47 |
+
raise NotImplementedError
|
| 48 |
+
|
| 49 |
+
def resolve_ref_schema(self, maybe_ref_json_schema: JsonSchemaValue, /) -> JsonSchemaValue:
|
| 50 |
+
"""Get the real schema for a `{"$ref": ...}` schema.
|
| 51 |
+
If the schema given is not a `$ref` schema, it will be returned as is.
|
| 52 |
+
This means you don't have to check before calling this function.
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
maybe_ref_json_schema: A JsonSchemaValue which may be a `$ref` schema.
|
| 56 |
+
|
| 57 |
+
Raises:
|
| 58 |
+
LookupError: If the ref is not found.
|
| 59 |
+
|
| 60 |
+
Returns:
|
| 61 |
+
JsonSchemaValue: A JsonSchemaValue that has no `$ref`.
|
| 62 |
+
"""
|
| 63 |
+
raise NotImplementedError
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class GetCoreSchemaHandler:
|
| 67 |
+
"""Handler to call into the next CoreSchema schema generation function."""
|
| 68 |
+
|
| 69 |
+
def __call__(self, source_type: Any, /) -> core_schema.CoreSchema:
|
| 70 |
+
"""Call the inner handler and get the CoreSchema it returns.
|
| 71 |
+
This will call the next CoreSchema modifying function up until it calls
|
| 72 |
+
into Pydantic's internal schema generation machinery, which will raise a
|
| 73 |
+
`pydantic.errors.PydanticSchemaGenerationError` error if it cannot generate
|
| 74 |
+
a CoreSchema for the given source type.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
source_type: The input type.
|
| 78 |
+
|
| 79 |
+
Returns:
|
| 80 |
+
CoreSchema: The `pydantic-core` CoreSchema generated.
|
| 81 |
+
"""
|
| 82 |
+
raise NotImplementedError
|
| 83 |
+
|
| 84 |
+
def generate_schema(self, source_type: Any, /) -> core_schema.CoreSchema:
|
| 85 |
+
"""Generate a schema unrelated to the current context.
|
| 86 |
+
Use this function if e.g. you are handling schema generation for a sequence
|
| 87 |
+
and want to generate a schema for its items.
|
| 88 |
+
Otherwise, you may end up doing something like applying a `min_length` constraint
|
| 89 |
+
that was intended for the sequence itself to its items!
|
| 90 |
+
|
| 91 |
+
Args:
|
| 92 |
+
source_type: The input type.
|
| 93 |
+
|
| 94 |
+
Returns:
|
| 95 |
+
CoreSchema: The `pydantic-core` CoreSchema generated.
|
| 96 |
+
"""
|
| 97 |
+
raise NotImplementedError
|
| 98 |
+
|
| 99 |
+
def resolve_ref_schema(self, maybe_ref_schema: core_schema.CoreSchema, /) -> core_schema.CoreSchema:
|
| 100 |
+
"""Get the real schema for a `definition-ref` schema.
|
| 101 |
+
If the schema given is not a `definition-ref` schema, it will be returned as is.
|
| 102 |
+
This means you don't have to check before calling this function.
|
| 103 |
+
|
| 104 |
+
Args:
|
| 105 |
+
maybe_ref_schema: A `CoreSchema`, `ref`-based or not.
|
| 106 |
+
|
| 107 |
+
Raises:
|
| 108 |
+
LookupError: If the `ref` is not found.
|
| 109 |
+
|
| 110 |
+
Returns:
|
| 111 |
+
A concrete `CoreSchema`.
|
| 112 |
+
"""
|
| 113 |
+
raise NotImplementedError
|
| 114 |
+
|
| 115 |
+
@property
|
| 116 |
+
def field_name(self) -> str | None:
|
| 117 |
+
"""Get the name of the closest field to this validator."""
|
| 118 |
+
raise NotImplementedError
|
| 119 |
+
|
| 120 |
+
def _get_types_namespace(self) -> NamespacesTuple:
|
| 121 |
+
"""Internal method used during type resolution for serializer annotations."""
|
| 122 |
+
raise NotImplementedError
|
vllm/lib/python3.10/site-packages/pydantic/class_validators.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""`class_validators` module is a backport module from V1."""
|
| 2 |
+
|
| 3 |
+
from ._migration import getattr_migration
|
| 4 |
+
|
| 5 |
+
__getattr__ = getattr_migration(__name__)
|
vllm/lib/python3.10/site-packages/pydantic/color.py
ADDED
|
@@ -0,0 +1,604 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Color definitions are used as per the CSS3
|
| 2 |
+
[CSS Color Module Level 3](http://www.w3.org/TR/css3-color/#svg-color) specification.
|
| 3 |
+
|
| 4 |
+
A few colors have multiple names referring to the sames colors, eg. `grey` and `gray` or `aqua` and `cyan`.
|
| 5 |
+
|
| 6 |
+
In these cases the _last_ color when sorted alphabetically takes preferences,
|
| 7 |
+
eg. `Color((0, 255, 255)).as_named() == 'cyan'` because "cyan" comes after "aqua".
|
| 8 |
+
|
| 9 |
+
Warning: Deprecated
|
| 10 |
+
The `Color` class is deprecated, use `pydantic_extra_types` instead.
|
| 11 |
+
See [`pydantic-extra-types.Color`](../usage/types/extra_types/color_types.md)
|
| 12 |
+
for more information.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import math
|
| 16 |
+
import re
|
| 17 |
+
from colorsys import hls_to_rgb, rgb_to_hls
|
| 18 |
+
from typing import Any, Callable, Optional, Tuple, Type, Union, cast
|
| 19 |
+
|
| 20 |
+
from pydantic_core import CoreSchema, PydanticCustomError, core_schema
|
| 21 |
+
from typing_extensions import deprecated
|
| 22 |
+
|
| 23 |
+
from ._internal import _repr
|
| 24 |
+
from ._internal._schema_generation_shared import GetJsonSchemaHandler as _GetJsonSchemaHandler
|
| 25 |
+
from .json_schema import JsonSchemaValue
|
| 26 |
+
from .warnings import PydanticDeprecatedSince20
|
| 27 |
+
|
| 28 |
+
ColorTuple = Union[Tuple[int, int, int], Tuple[int, int, int, float]]
|
| 29 |
+
ColorType = Union[ColorTuple, str]
|
| 30 |
+
HslColorTuple = Union[Tuple[float, float, float], Tuple[float, float, float, float]]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class RGBA:
|
| 34 |
+
"""Internal use only as a representation of a color."""
|
| 35 |
+
|
| 36 |
+
__slots__ = 'r', 'g', 'b', 'alpha', '_tuple'
|
| 37 |
+
|
| 38 |
+
def __init__(self, r: float, g: float, b: float, alpha: Optional[float]):
|
| 39 |
+
self.r = r
|
| 40 |
+
self.g = g
|
| 41 |
+
self.b = b
|
| 42 |
+
self.alpha = alpha
|
| 43 |
+
|
| 44 |
+
self._tuple: Tuple[float, float, float, Optional[float]] = (r, g, b, alpha)
|
| 45 |
+
|
| 46 |
+
def __getitem__(self, item: Any) -> Any:
|
| 47 |
+
return self._tuple[item]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# these are not compiled here to avoid import slowdown, they'll be compiled the first time they're used, then cached
|
| 51 |
+
_r_255 = r'(\d{1,3}(?:\.\d+)?)'
|
| 52 |
+
_r_comma = r'\s*,\s*'
|
| 53 |
+
_r_alpha = r'(\d(?:\.\d+)?|\.\d+|\d{1,2}%)'
|
| 54 |
+
_r_h = r'(-?\d+(?:\.\d+)?|-?\.\d+)(deg|rad|turn)?'
|
| 55 |
+
_r_sl = r'(\d{1,3}(?:\.\d+)?)%'
|
| 56 |
+
r_hex_short = r'\s*(?:#|0x)?([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])?\s*'
|
| 57 |
+
r_hex_long = r'\s*(?:#|0x)?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?\s*'
|
| 58 |
+
# CSS3 RGB examples: rgb(0, 0, 0), rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 50%)
|
| 59 |
+
r_rgb = rf'\s*rgba?\(\s*{_r_255}{_r_comma}{_r_255}{_r_comma}{_r_255}(?:{_r_comma}{_r_alpha})?\s*\)\s*'
|
| 60 |
+
# CSS3 HSL examples: hsl(270, 60%, 50%), hsla(270, 60%, 50%, 0.5), hsla(270, 60%, 50%, 50%)
|
| 61 |
+
r_hsl = rf'\s*hsla?\(\s*{_r_h}{_r_comma}{_r_sl}{_r_comma}{_r_sl}(?:{_r_comma}{_r_alpha})?\s*\)\s*'
|
| 62 |
+
# CSS4 RGB examples: rgb(0 0 0), rgb(0 0 0 / 0.5), rgb(0 0 0 / 50%), rgba(0 0 0 / 50%)
|
| 63 |
+
r_rgb_v4_style = rf'\s*rgba?\(\s*{_r_255}\s+{_r_255}\s+{_r_255}(?:\s*/\s*{_r_alpha})?\s*\)\s*'
|
| 64 |
+
# CSS4 HSL examples: hsl(270 60% 50%), hsl(270 60% 50% / 0.5), hsl(270 60% 50% / 50%), hsla(270 60% 50% / 50%)
|
| 65 |
+
r_hsl_v4_style = rf'\s*hsla?\(\s*{_r_h}\s+{_r_sl}\s+{_r_sl}(?:\s*/\s*{_r_alpha})?\s*\)\s*'
|
| 66 |
+
|
| 67 |
+
# colors where the two hex characters are the same, if all colors match this the short version of hex colors can be used
|
| 68 |
+
repeat_colors = {int(c * 2, 16) for c in '0123456789abcdef'}
|
| 69 |
+
rads = 2 * math.pi
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@deprecated(
|
| 73 |
+
'The `Color` class is deprecated, use `pydantic_extra_types` instead. '
|
| 74 |
+
'See https://docs.pydantic.dev/latest/api/pydantic_extra_types_color/.',
|
| 75 |
+
category=PydanticDeprecatedSince20,
|
| 76 |
+
)
|
| 77 |
+
class Color(_repr.Representation):
|
| 78 |
+
"""Represents a color."""
|
| 79 |
+
|
| 80 |
+
__slots__ = '_original', '_rgba'
|
| 81 |
+
|
| 82 |
+
def __init__(self, value: ColorType) -> None:
|
| 83 |
+
self._rgba: RGBA
|
| 84 |
+
self._original: ColorType
|
| 85 |
+
if isinstance(value, (tuple, list)):
|
| 86 |
+
self._rgba = parse_tuple(value)
|
| 87 |
+
elif isinstance(value, str):
|
| 88 |
+
self._rgba = parse_str(value)
|
| 89 |
+
elif isinstance(value, Color):
|
| 90 |
+
self._rgba = value._rgba
|
| 91 |
+
value = value._original
|
| 92 |
+
else:
|
| 93 |
+
raise PydanticCustomError(
|
| 94 |
+
'color_error', 'value is not a valid color: value must be a tuple, list or string'
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
# if we've got here value must be a valid color
|
| 98 |
+
self._original = value
|
| 99 |
+
|
| 100 |
+
@classmethod
|
| 101 |
+
def __get_pydantic_json_schema__(
|
| 102 |
+
cls, core_schema: core_schema.CoreSchema, handler: _GetJsonSchemaHandler
|
| 103 |
+
) -> JsonSchemaValue:
|
| 104 |
+
field_schema = {}
|
| 105 |
+
field_schema.update(type='string', format='color')
|
| 106 |
+
return field_schema
|
| 107 |
+
|
| 108 |
+
def original(self) -> ColorType:
|
| 109 |
+
"""Original value passed to `Color`."""
|
| 110 |
+
return self._original
|
| 111 |
+
|
| 112 |
+
def as_named(self, *, fallback: bool = False) -> str:
|
| 113 |
+
"""Returns the name of the color if it can be found in `COLORS_BY_VALUE` dictionary,
|
| 114 |
+
otherwise returns the hexadecimal representation of the color or raises `ValueError`.
|
| 115 |
+
|
| 116 |
+
Args:
|
| 117 |
+
fallback: If True, falls back to returning the hexadecimal representation of
|
| 118 |
+
the color instead of raising a ValueError when no named color is found.
|
| 119 |
+
|
| 120 |
+
Returns:
|
| 121 |
+
The name of the color, or the hexadecimal representation of the color.
|
| 122 |
+
|
| 123 |
+
Raises:
|
| 124 |
+
ValueError: When no named color is found and fallback is `False`.
|
| 125 |
+
"""
|
| 126 |
+
if self._rgba.alpha is None:
|
| 127 |
+
rgb = cast(Tuple[int, int, int], self.as_rgb_tuple())
|
| 128 |
+
try:
|
| 129 |
+
return COLORS_BY_VALUE[rgb]
|
| 130 |
+
except KeyError as e:
|
| 131 |
+
if fallback:
|
| 132 |
+
return self.as_hex()
|
| 133 |
+
else:
|
| 134 |
+
raise ValueError('no named color found, use fallback=True, as_hex() or as_rgb()') from e
|
| 135 |
+
else:
|
| 136 |
+
return self.as_hex()
|
| 137 |
+
|
| 138 |
+
def as_hex(self) -> str:
|
| 139 |
+
"""Returns the hexadecimal representation of the color.
|
| 140 |
+
|
| 141 |
+
Hex string representing the color can be 3, 4, 6, or 8 characters depending on whether the string
|
| 142 |
+
a "short" representation of the color is possible and whether there's an alpha channel.
|
| 143 |
+
|
| 144 |
+
Returns:
|
| 145 |
+
The hexadecimal representation of the color.
|
| 146 |
+
"""
|
| 147 |
+
values = [float_to_255(c) for c in self._rgba[:3]]
|
| 148 |
+
if self._rgba.alpha is not None:
|
| 149 |
+
values.append(float_to_255(self._rgba.alpha))
|
| 150 |
+
|
| 151 |
+
as_hex = ''.join(f'{v:02x}' for v in values)
|
| 152 |
+
if all(c in repeat_colors for c in values):
|
| 153 |
+
as_hex = ''.join(as_hex[c] for c in range(0, len(as_hex), 2))
|
| 154 |
+
return '#' + as_hex
|
| 155 |
+
|
| 156 |
+
def as_rgb(self) -> str:
|
| 157 |
+
"""Color as an `rgb(<r>, <g>, <b>)` or `rgba(<r>, <g>, <b>, <a>)` string."""
|
| 158 |
+
if self._rgba.alpha is None:
|
| 159 |
+
return f'rgb({float_to_255(self._rgba.r)}, {float_to_255(self._rgba.g)}, {float_to_255(self._rgba.b)})'
|
| 160 |
+
else:
|
| 161 |
+
return (
|
| 162 |
+
f'rgba({float_to_255(self._rgba.r)}, {float_to_255(self._rgba.g)}, {float_to_255(self._rgba.b)}, '
|
| 163 |
+
f'{round(self._alpha_float(), 2)})'
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
def as_rgb_tuple(self, *, alpha: Optional[bool] = None) -> ColorTuple:
|
| 167 |
+
"""Returns the color as an RGB or RGBA tuple.
|
| 168 |
+
|
| 169 |
+
Args:
|
| 170 |
+
alpha: Whether to include the alpha channel. There are three options for this input:
|
| 171 |
+
|
| 172 |
+
- `None` (default): Include alpha only if it's set. (e.g. not `None`)
|
| 173 |
+
- `True`: Always include alpha.
|
| 174 |
+
- `False`: Always omit alpha.
|
| 175 |
+
|
| 176 |
+
Returns:
|
| 177 |
+
A tuple that contains the values of the red, green, and blue channels in the range 0 to 255.
|
| 178 |
+
If alpha is included, it is in the range 0 to 1.
|
| 179 |
+
"""
|
| 180 |
+
r, g, b = (float_to_255(c) for c in self._rgba[:3])
|
| 181 |
+
if alpha is None:
|
| 182 |
+
if self._rgba.alpha is None:
|
| 183 |
+
return r, g, b
|
| 184 |
+
else:
|
| 185 |
+
return r, g, b, self._alpha_float()
|
| 186 |
+
elif alpha:
|
| 187 |
+
return r, g, b, self._alpha_float()
|
| 188 |
+
else:
|
| 189 |
+
# alpha is False
|
| 190 |
+
return r, g, b
|
| 191 |
+
|
| 192 |
+
def as_hsl(self) -> str:
|
| 193 |
+
"""Color as an `hsl(<h>, <s>, <l>)` or `hsl(<h>, <s>, <l>, <a>)` string."""
|
| 194 |
+
if self._rgba.alpha is None:
|
| 195 |
+
h, s, li = self.as_hsl_tuple(alpha=False) # type: ignore
|
| 196 |
+
return f'hsl({h * 360:0.0f}, {s:0.0%}, {li:0.0%})'
|
| 197 |
+
else:
|
| 198 |
+
h, s, li, a = self.as_hsl_tuple(alpha=True) # type: ignore
|
| 199 |
+
return f'hsl({h * 360:0.0f}, {s:0.0%}, {li:0.0%}, {round(a, 2)})'
|
| 200 |
+
|
| 201 |
+
def as_hsl_tuple(self, *, alpha: Optional[bool] = None) -> HslColorTuple:
|
| 202 |
+
"""Returns the color as an HSL or HSLA tuple.
|
| 203 |
+
|
| 204 |
+
Args:
|
| 205 |
+
alpha: Whether to include the alpha channel.
|
| 206 |
+
|
| 207 |
+
- `None` (default): Include the alpha channel only if it's set (e.g. not `None`).
|
| 208 |
+
- `True`: Always include alpha.
|
| 209 |
+
- `False`: Always omit alpha.
|
| 210 |
+
|
| 211 |
+
Returns:
|
| 212 |
+
The color as a tuple of hue, saturation, lightness, and alpha (if included).
|
| 213 |
+
All elements are in the range 0 to 1.
|
| 214 |
+
|
| 215 |
+
Note:
|
| 216 |
+
This is HSL as used in HTML and most other places, not HLS as used in Python's `colorsys`.
|
| 217 |
+
"""
|
| 218 |
+
h, l, s = rgb_to_hls(self._rgba.r, self._rgba.g, self._rgba.b) # noqa: E741
|
| 219 |
+
if alpha is None:
|
| 220 |
+
if self._rgba.alpha is None:
|
| 221 |
+
return h, s, l
|
| 222 |
+
else:
|
| 223 |
+
return h, s, l, self._alpha_float()
|
| 224 |
+
if alpha:
|
| 225 |
+
return h, s, l, self._alpha_float()
|
| 226 |
+
else:
|
| 227 |
+
# alpha is False
|
| 228 |
+
return h, s, l
|
| 229 |
+
|
| 230 |
+
def _alpha_float(self) -> float:
|
| 231 |
+
return 1 if self._rgba.alpha is None else self._rgba.alpha
|
| 232 |
+
|
| 233 |
+
@classmethod
|
| 234 |
+
def __get_pydantic_core_schema__(
|
| 235 |
+
cls, source: Type[Any], handler: Callable[[Any], CoreSchema]
|
| 236 |
+
) -> core_schema.CoreSchema:
|
| 237 |
+
return core_schema.with_info_plain_validator_function(
|
| 238 |
+
cls._validate, serialization=core_schema.to_string_ser_schema()
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
@classmethod
|
| 242 |
+
def _validate(cls, __input_value: Any, _: Any) -> 'Color':
|
| 243 |
+
return cls(__input_value)
|
| 244 |
+
|
| 245 |
+
def __str__(self) -> str:
|
| 246 |
+
return self.as_named(fallback=True)
|
| 247 |
+
|
| 248 |
+
def __repr_args__(self) -> '_repr.ReprArgs':
|
| 249 |
+
return [(None, self.as_named(fallback=True))] + [('rgb', self.as_rgb_tuple())]
|
| 250 |
+
|
| 251 |
+
def __eq__(self, other: Any) -> bool:
|
| 252 |
+
return isinstance(other, Color) and self.as_rgb_tuple() == other.as_rgb_tuple()
|
| 253 |
+
|
| 254 |
+
def __hash__(self) -> int:
|
| 255 |
+
return hash(self.as_rgb_tuple())
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def parse_tuple(value: Tuple[Any, ...]) -> RGBA:
|
| 259 |
+
"""Parse a tuple or list to get RGBA values.
|
| 260 |
+
|
| 261 |
+
Args:
|
| 262 |
+
value: A tuple or list.
|
| 263 |
+
|
| 264 |
+
Returns:
|
| 265 |
+
An `RGBA` tuple parsed from the input tuple.
|
| 266 |
+
|
| 267 |
+
Raises:
|
| 268 |
+
PydanticCustomError: If tuple is not valid.
|
| 269 |
+
"""
|
| 270 |
+
if len(value) == 3:
|
| 271 |
+
r, g, b = (parse_color_value(v) for v in value)
|
| 272 |
+
return RGBA(r, g, b, None)
|
| 273 |
+
elif len(value) == 4:
|
| 274 |
+
r, g, b = (parse_color_value(v) for v in value[:3])
|
| 275 |
+
return RGBA(r, g, b, parse_float_alpha(value[3]))
|
| 276 |
+
else:
|
| 277 |
+
raise PydanticCustomError('color_error', 'value is not a valid color: tuples must have length 3 or 4')
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def parse_str(value: str) -> RGBA:
|
| 281 |
+
"""Parse a string representing a color to an RGBA tuple.
|
| 282 |
+
|
| 283 |
+
Possible formats for the input string include:
|
| 284 |
+
|
| 285 |
+
* named color, see `COLORS_BY_NAME`
|
| 286 |
+
* hex short eg. `<prefix>fff` (prefix can be `#`, `0x` or nothing)
|
| 287 |
+
* hex long eg. `<prefix>ffffff` (prefix can be `#`, `0x` or nothing)
|
| 288 |
+
* `rgb(<r>, <g>, <b>)`
|
| 289 |
+
* `rgba(<r>, <g>, <b>, <a>)`
|
| 290 |
+
|
| 291 |
+
Args:
|
| 292 |
+
value: A string representing a color.
|
| 293 |
+
|
| 294 |
+
Returns:
|
| 295 |
+
An `RGBA` tuple parsed from the input string.
|
| 296 |
+
|
| 297 |
+
Raises:
|
| 298 |
+
ValueError: If the input string cannot be parsed to an RGBA tuple.
|
| 299 |
+
"""
|
| 300 |
+
value_lower = value.lower()
|
| 301 |
+
try:
|
| 302 |
+
r, g, b = COLORS_BY_NAME[value_lower]
|
| 303 |
+
except KeyError:
|
| 304 |
+
pass
|
| 305 |
+
else:
|
| 306 |
+
return ints_to_rgba(r, g, b, None)
|
| 307 |
+
|
| 308 |
+
m = re.fullmatch(r_hex_short, value_lower)
|
| 309 |
+
if m:
|
| 310 |
+
*rgb, a = m.groups()
|
| 311 |
+
r, g, b = (int(v * 2, 16) for v in rgb)
|
| 312 |
+
if a:
|
| 313 |
+
alpha: Optional[float] = int(a * 2, 16) / 255
|
| 314 |
+
else:
|
| 315 |
+
alpha = None
|
| 316 |
+
return ints_to_rgba(r, g, b, alpha)
|
| 317 |
+
|
| 318 |
+
m = re.fullmatch(r_hex_long, value_lower)
|
| 319 |
+
if m:
|
| 320 |
+
*rgb, a = m.groups()
|
| 321 |
+
r, g, b = (int(v, 16) for v in rgb)
|
| 322 |
+
if a:
|
| 323 |
+
alpha = int(a, 16) / 255
|
| 324 |
+
else:
|
| 325 |
+
alpha = None
|
| 326 |
+
return ints_to_rgba(r, g, b, alpha)
|
| 327 |
+
|
| 328 |
+
m = re.fullmatch(r_rgb, value_lower) or re.fullmatch(r_rgb_v4_style, value_lower)
|
| 329 |
+
if m:
|
| 330 |
+
return ints_to_rgba(*m.groups()) # type: ignore
|
| 331 |
+
|
| 332 |
+
m = re.fullmatch(r_hsl, value_lower) or re.fullmatch(r_hsl_v4_style, value_lower)
|
| 333 |
+
if m:
|
| 334 |
+
return parse_hsl(*m.groups()) # type: ignore
|
| 335 |
+
|
| 336 |
+
raise PydanticCustomError('color_error', 'value is not a valid color: string not recognised as a valid color')
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def ints_to_rgba(r: Union[int, str], g: Union[int, str], b: Union[int, str], alpha: Optional[float] = None) -> RGBA:
|
| 340 |
+
"""Converts integer or string values for RGB color and an optional alpha value to an `RGBA` object.
|
| 341 |
+
|
| 342 |
+
Args:
|
| 343 |
+
r: An integer or string representing the red color value.
|
| 344 |
+
g: An integer or string representing the green color value.
|
| 345 |
+
b: An integer or string representing the blue color value.
|
| 346 |
+
alpha: A float representing the alpha value. Defaults to None.
|
| 347 |
+
|
| 348 |
+
Returns:
|
| 349 |
+
An instance of the `RGBA` class with the corresponding color and alpha values.
|
| 350 |
+
"""
|
| 351 |
+
return RGBA(parse_color_value(r), parse_color_value(g), parse_color_value(b), parse_float_alpha(alpha))
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def parse_color_value(value: Union[int, str], max_val: int = 255) -> float:
|
| 355 |
+
"""Parse the color value provided and return a number between 0 and 1.
|
| 356 |
+
|
| 357 |
+
Args:
|
| 358 |
+
value: An integer or string color value.
|
| 359 |
+
max_val: Maximum range value. Defaults to 255.
|
| 360 |
+
|
| 361 |
+
Raises:
|
| 362 |
+
PydanticCustomError: If the value is not a valid color.
|
| 363 |
+
|
| 364 |
+
Returns:
|
| 365 |
+
A number between 0 and 1.
|
| 366 |
+
"""
|
| 367 |
+
try:
|
| 368 |
+
color = float(value)
|
| 369 |
+
except ValueError:
|
| 370 |
+
raise PydanticCustomError('color_error', 'value is not a valid color: color values must be a valid number')
|
| 371 |
+
if 0 <= color <= max_val:
|
| 372 |
+
return color / max_val
|
| 373 |
+
else:
|
| 374 |
+
raise PydanticCustomError(
|
| 375 |
+
'color_error',
|
| 376 |
+
'value is not a valid color: color values must be in the range 0 to {max_val}',
|
| 377 |
+
{'max_val': max_val},
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def parse_float_alpha(value: Union[None, str, float, int]) -> Optional[float]:
|
| 382 |
+
"""Parse an alpha value checking it's a valid float in the range 0 to 1.
|
| 383 |
+
|
| 384 |
+
Args:
|
| 385 |
+
value: The input value to parse.
|
| 386 |
+
|
| 387 |
+
Returns:
|
| 388 |
+
The parsed value as a float, or `None` if the value was None or equal 1.
|
| 389 |
+
|
| 390 |
+
Raises:
|
| 391 |
+
PydanticCustomError: If the input value cannot be successfully parsed as a float in the expected range.
|
| 392 |
+
"""
|
| 393 |
+
if value is None:
|
| 394 |
+
return None
|
| 395 |
+
try:
|
| 396 |
+
if isinstance(value, str) and value.endswith('%'):
|
| 397 |
+
alpha = float(value[:-1]) / 100
|
| 398 |
+
else:
|
| 399 |
+
alpha = float(value)
|
| 400 |
+
except ValueError:
|
| 401 |
+
raise PydanticCustomError('color_error', 'value is not a valid color: alpha values must be a valid float')
|
| 402 |
+
|
| 403 |
+
if math.isclose(alpha, 1):
|
| 404 |
+
return None
|
| 405 |
+
elif 0 <= alpha <= 1:
|
| 406 |
+
return alpha
|
| 407 |
+
else:
|
| 408 |
+
raise PydanticCustomError('color_error', 'value is not a valid color: alpha values must be in the range 0 to 1')
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def parse_hsl(h: str, h_units: str, sat: str, light: str, alpha: Optional[float] = None) -> RGBA:
|
| 412 |
+
"""Parse raw hue, saturation, lightness, and alpha values and convert to RGBA.
|
| 413 |
+
|
| 414 |
+
Args:
|
| 415 |
+
h: The hue value.
|
| 416 |
+
h_units: The unit for hue value.
|
| 417 |
+
sat: The saturation value.
|
| 418 |
+
light: The lightness value.
|
| 419 |
+
alpha: Alpha value.
|
| 420 |
+
|
| 421 |
+
Returns:
|
| 422 |
+
An instance of `RGBA`.
|
| 423 |
+
"""
|
| 424 |
+
s_value, l_value = parse_color_value(sat, 100), parse_color_value(light, 100)
|
| 425 |
+
|
| 426 |
+
h_value = float(h)
|
| 427 |
+
if h_units in {None, 'deg'}:
|
| 428 |
+
h_value = h_value % 360 / 360
|
| 429 |
+
elif h_units == 'rad':
|
| 430 |
+
h_value = h_value % rads / rads
|
| 431 |
+
else:
|
| 432 |
+
# turns
|
| 433 |
+
h_value = h_value % 1
|
| 434 |
+
|
| 435 |
+
r, g, b = hls_to_rgb(h_value, l_value, s_value)
|
| 436 |
+
return RGBA(r, g, b, parse_float_alpha(alpha))
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def float_to_255(c: float) -> int:
|
| 440 |
+
"""Converts a float value between 0 and 1 (inclusive) to an integer between 0 and 255 (inclusive).
|
| 441 |
+
|
| 442 |
+
Args:
|
| 443 |
+
c: The float value to be converted. Must be between 0 and 1 (inclusive).
|
| 444 |
+
|
| 445 |
+
Returns:
|
| 446 |
+
The integer equivalent of the given float value rounded to the nearest whole number.
|
| 447 |
+
|
| 448 |
+
Raises:
|
| 449 |
+
ValueError: If the given float value is outside the acceptable range of 0 to 1 (inclusive).
|
| 450 |
+
"""
|
| 451 |
+
return int(round(c * 255))
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
COLORS_BY_NAME = {
|
| 455 |
+
'aliceblue': (240, 248, 255),
|
| 456 |
+
'antiquewhite': (250, 235, 215),
|
| 457 |
+
'aqua': (0, 255, 255),
|
| 458 |
+
'aquamarine': (127, 255, 212),
|
| 459 |
+
'azure': (240, 255, 255),
|
| 460 |
+
'beige': (245, 245, 220),
|
| 461 |
+
'bisque': (255, 228, 196),
|
| 462 |
+
'black': (0, 0, 0),
|
| 463 |
+
'blanchedalmond': (255, 235, 205),
|
| 464 |
+
'blue': (0, 0, 255),
|
| 465 |
+
'blueviolet': (138, 43, 226),
|
| 466 |
+
'brown': (165, 42, 42),
|
| 467 |
+
'burlywood': (222, 184, 135),
|
| 468 |
+
'cadetblue': (95, 158, 160),
|
| 469 |
+
'chartreuse': (127, 255, 0),
|
| 470 |
+
'chocolate': (210, 105, 30),
|
| 471 |
+
'coral': (255, 127, 80),
|
| 472 |
+
'cornflowerblue': (100, 149, 237),
|
| 473 |
+
'cornsilk': (255, 248, 220),
|
| 474 |
+
'crimson': (220, 20, 60),
|
| 475 |
+
'cyan': (0, 255, 255),
|
| 476 |
+
'darkblue': (0, 0, 139),
|
| 477 |
+
'darkcyan': (0, 139, 139),
|
| 478 |
+
'darkgoldenrod': (184, 134, 11),
|
| 479 |
+
'darkgray': (169, 169, 169),
|
| 480 |
+
'darkgreen': (0, 100, 0),
|
| 481 |
+
'darkgrey': (169, 169, 169),
|
| 482 |
+
'darkkhaki': (189, 183, 107),
|
| 483 |
+
'darkmagenta': (139, 0, 139),
|
| 484 |
+
'darkolivegreen': (85, 107, 47),
|
| 485 |
+
'darkorange': (255, 140, 0),
|
| 486 |
+
'darkorchid': (153, 50, 204),
|
| 487 |
+
'darkred': (139, 0, 0),
|
| 488 |
+
'darksalmon': (233, 150, 122),
|
| 489 |
+
'darkseagreen': (143, 188, 143),
|
| 490 |
+
'darkslateblue': (72, 61, 139),
|
| 491 |
+
'darkslategray': (47, 79, 79),
|
| 492 |
+
'darkslategrey': (47, 79, 79),
|
| 493 |
+
'darkturquoise': (0, 206, 209),
|
| 494 |
+
'darkviolet': (148, 0, 211),
|
| 495 |
+
'deeppink': (255, 20, 147),
|
| 496 |
+
'deepskyblue': (0, 191, 255),
|
| 497 |
+
'dimgray': (105, 105, 105),
|
| 498 |
+
'dimgrey': (105, 105, 105),
|
| 499 |
+
'dodgerblue': (30, 144, 255),
|
| 500 |
+
'firebrick': (178, 34, 34),
|
| 501 |
+
'floralwhite': (255, 250, 240),
|
| 502 |
+
'forestgreen': (34, 139, 34),
|
| 503 |
+
'fuchsia': (255, 0, 255),
|
| 504 |
+
'gainsboro': (220, 220, 220),
|
| 505 |
+
'ghostwhite': (248, 248, 255),
|
| 506 |
+
'gold': (255, 215, 0),
|
| 507 |
+
'goldenrod': (218, 165, 32),
|
| 508 |
+
'gray': (128, 128, 128),
|
| 509 |
+
'green': (0, 128, 0),
|
| 510 |
+
'greenyellow': (173, 255, 47),
|
| 511 |
+
'grey': (128, 128, 128),
|
| 512 |
+
'honeydew': (240, 255, 240),
|
| 513 |
+
'hotpink': (255, 105, 180),
|
| 514 |
+
'indianred': (205, 92, 92),
|
| 515 |
+
'indigo': (75, 0, 130),
|
| 516 |
+
'ivory': (255, 255, 240),
|
| 517 |
+
'khaki': (240, 230, 140),
|
| 518 |
+
'lavender': (230, 230, 250),
|
| 519 |
+
'lavenderblush': (255, 240, 245),
|
| 520 |
+
'lawngreen': (124, 252, 0),
|
| 521 |
+
'lemonchiffon': (255, 250, 205),
|
| 522 |
+
'lightblue': (173, 216, 230),
|
| 523 |
+
'lightcoral': (240, 128, 128),
|
| 524 |
+
'lightcyan': (224, 255, 255),
|
| 525 |
+
'lightgoldenrodyellow': (250, 250, 210),
|
| 526 |
+
'lightgray': (211, 211, 211),
|
| 527 |
+
'lightgreen': (144, 238, 144),
|
| 528 |
+
'lightgrey': (211, 211, 211),
|
| 529 |
+
'lightpink': (255, 182, 193),
|
| 530 |
+
'lightsalmon': (255, 160, 122),
|
| 531 |
+
'lightseagreen': (32, 178, 170),
|
| 532 |
+
'lightskyblue': (135, 206, 250),
|
| 533 |
+
'lightslategray': (119, 136, 153),
|
| 534 |
+
'lightslategrey': (119, 136, 153),
|
| 535 |
+
'lightsteelblue': (176, 196, 222),
|
| 536 |
+
'lightyellow': (255, 255, 224),
|
| 537 |
+
'lime': (0, 255, 0),
|
| 538 |
+
'limegreen': (50, 205, 50),
|
| 539 |
+
'linen': (250, 240, 230),
|
| 540 |
+
'magenta': (255, 0, 255),
|
| 541 |
+
'maroon': (128, 0, 0),
|
| 542 |
+
'mediumaquamarine': (102, 205, 170),
|
| 543 |
+
'mediumblue': (0, 0, 205),
|
| 544 |
+
'mediumorchid': (186, 85, 211),
|
| 545 |
+
'mediumpurple': (147, 112, 219),
|
| 546 |
+
'mediumseagreen': (60, 179, 113),
|
| 547 |
+
'mediumslateblue': (123, 104, 238),
|
| 548 |
+
'mediumspringgreen': (0, 250, 154),
|
| 549 |
+
'mediumturquoise': (72, 209, 204),
|
| 550 |
+
'mediumvioletred': (199, 21, 133),
|
| 551 |
+
'midnightblue': (25, 25, 112),
|
| 552 |
+
'mintcream': (245, 255, 250),
|
| 553 |
+
'mistyrose': (255, 228, 225),
|
| 554 |
+
'moccasin': (255, 228, 181),
|
| 555 |
+
'navajowhite': (255, 222, 173),
|
| 556 |
+
'navy': (0, 0, 128),
|
| 557 |
+
'oldlace': (253, 245, 230),
|
| 558 |
+
'olive': (128, 128, 0),
|
| 559 |
+
'olivedrab': (107, 142, 35),
|
| 560 |
+
'orange': (255, 165, 0),
|
| 561 |
+
'orangered': (255, 69, 0),
|
| 562 |
+
'orchid': (218, 112, 214),
|
| 563 |
+
'palegoldenrod': (238, 232, 170),
|
| 564 |
+
'palegreen': (152, 251, 152),
|
| 565 |
+
'paleturquoise': (175, 238, 238),
|
| 566 |
+
'palevioletred': (219, 112, 147),
|
| 567 |
+
'papayawhip': (255, 239, 213),
|
| 568 |
+
'peachpuff': (255, 218, 185),
|
| 569 |
+
'peru': (205, 133, 63),
|
| 570 |
+
'pink': (255, 192, 203),
|
| 571 |
+
'plum': (221, 160, 221),
|
| 572 |
+
'powderblue': (176, 224, 230),
|
| 573 |
+
'purple': (128, 0, 128),
|
| 574 |
+
'red': (255, 0, 0),
|
| 575 |
+
'rosybrown': (188, 143, 143),
|
| 576 |
+
'royalblue': (65, 105, 225),
|
| 577 |
+
'saddlebrown': (139, 69, 19),
|
| 578 |
+
'salmon': (250, 128, 114),
|
| 579 |
+
'sandybrown': (244, 164, 96),
|
| 580 |
+
'seagreen': (46, 139, 87),
|
| 581 |
+
'seashell': (255, 245, 238),
|
| 582 |
+
'sienna': (160, 82, 45),
|
| 583 |
+
'silver': (192, 192, 192),
|
| 584 |
+
'skyblue': (135, 206, 235),
|
| 585 |
+
'slateblue': (106, 90, 205),
|
| 586 |
+
'slategray': (112, 128, 144),
|
| 587 |
+
'slategrey': (112, 128, 144),
|
| 588 |
+
'snow': (255, 250, 250),
|
| 589 |
+
'springgreen': (0, 255, 127),
|
| 590 |
+
'steelblue': (70, 130, 180),
|
| 591 |
+
'tan': (210, 180, 140),
|
| 592 |
+
'teal': (0, 128, 128),
|
| 593 |
+
'thistle': (216, 191, 216),
|
| 594 |
+
'tomato': (255, 99, 71),
|
| 595 |
+
'turquoise': (64, 224, 208),
|
| 596 |
+
'violet': (238, 130, 238),
|
| 597 |
+
'wheat': (245, 222, 179),
|
| 598 |
+
'white': (255, 255, 255),
|
| 599 |
+
'whitesmoke': (245, 245, 245),
|
| 600 |
+
'yellow': (255, 255, 0),
|
| 601 |
+
'yellowgreen': (154, 205, 50),
|
| 602 |
+
}
|
| 603 |
+
|
| 604 |
+
COLORS_BY_VALUE = {v: k for k, v in COLORS_BY_NAME.items()}
|
vllm/lib/python3.10/site-packages/pydantic/config.py
ADDED
|
@@ -0,0 +1,1049 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Configuration for Pydantic models."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations as _annotations
|
| 4 |
+
|
| 5 |
+
from re import Pattern
|
| 6 |
+
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Type, TypeVar, Union
|
| 7 |
+
|
| 8 |
+
from typing_extensions import Literal, TypeAlias, TypedDict
|
| 9 |
+
|
| 10 |
+
from ._migration import getattr_migration
|
| 11 |
+
from .aliases import AliasGenerator
|
| 12 |
+
from .errors import PydanticUserError
|
| 13 |
+
|
| 14 |
+
if TYPE_CHECKING:
|
| 15 |
+
from ._internal._generate_schema import GenerateSchema as _GenerateSchema
|
| 16 |
+
from .fields import ComputedFieldInfo, FieldInfo
|
| 17 |
+
|
| 18 |
+
__all__ = ('ConfigDict', 'with_config')
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
JsonValue: TypeAlias = Union[int, float, str, bool, None, List['JsonValue'], 'JsonDict']
|
| 22 |
+
JsonDict: TypeAlias = Dict[str, JsonValue]
|
| 23 |
+
|
| 24 |
+
JsonEncoder = Callable[[Any], Any]
|
| 25 |
+
|
| 26 |
+
JsonSchemaExtraCallable: TypeAlias = Union[
|
| 27 |
+
Callable[[JsonDict], None],
|
| 28 |
+
Callable[[JsonDict, Type[Any]], None],
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
ExtraValues = Literal['allow', 'ignore', 'forbid']
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class ConfigDict(TypedDict, total=False):
|
| 35 |
+
"""A TypedDict for configuring Pydantic behaviour."""
|
| 36 |
+
|
| 37 |
+
title: str | None
|
| 38 |
+
"""The title for the generated JSON schema, defaults to the model's name"""
|
| 39 |
+
|
| 40 |
+
model_title_generator: Callable[[type], str] | None
|
| 41 |
+
"""A callable that takes a model class and returns the title for it. Defaults to `None`."""
|
| 42 |
+
|
| 43 |
+
field_title_generator: Callable[[str, FieldInfo | ComputedFieldInfo], str] | None
|
| 44 |
+
"""A callable that takes a field's name and info and returns title for it. Defaults to `None`."""
|
| 45 |
+
|
| 46 |
+
str_to_lower: bool
|
| 47 |
+
"""Whether to convert all characters to lowercase for str types. Defaults to `False`."""
|
| 48 |
+
|
| 49 |
+
str_to_upper: bool
|
| 50 |
+
"""Whether to convert all characters to uppercase for str types. Defaults to `False`."""
|
| 51 |
+
|
| 52 |
+
str_strip_whitespace: bool
|
| 53 |
+
"""Whether to strip leading and trailing whitespace for str types."""
|
| 54 |
+
|
| 55 |
+
str_min_length: int
|
| 56 |
+
"""The minimum length for str types. Defaults to `None`."""
|
| 57 |
+
|
| 58 |
+
str_max_length: int | None
|
| 59 |
+
"""The maximum length for str types. Defaults to `None`."""
|
| 60 |
+
|
| 61 |
+
extra: ExtraValues | None
|
| 62 |
+
"""
|
| 63 |
+
Whether to ignore, allow, or forbid extra attributes during model initialization. Defaults to `'ignore'`.
|
| 64 |
+
|
| 65 |
+
You can configure how pydantic handles the attributes that are not defined in the model:
|
| 66 |
+
|
| 67 |
+
* `allow` - Allow any extra attributes.
|
| 68 |
+
* `forbid` - Forbid any extra attributes.
|
| 69 |
+
* `ignore` - Ignore any extra attributes.
|
| 70 |
+
|
| 71 |
+
```python
|
| 72 |
+
from pydantic import BaseModel, ConfigDict
|
| 73 |
+
|
| 74 |
+
class User(BaseModel):
|
| 75 |
+
model_config = ConfigDict(extra='ignore') # (1)!
|
| 76 |
+
|
| 77 |
+
name: str
|
| 78 |
+
|
| 79 |
+
user = User(name='John Doe', age=20) # (2)!
|
| 80 |
+
print(user)
|
| 81 |
+
#> name='John Doe'
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
1. This is the default behaviour.
|
| 85 |
+
2. The `age` argument is ignored.
|
| 86 |
+
|
| 87 |
+
Instead, with `extra='allow'`, the `age` argument is included:
|
| 88 |
+
|
| 89 |
+
```python
|
| 90 |
+
from pydantic import BaseModel, ConfigDict
|
| 91 |
+
|
| 92 |
+
class User(BaseModel):
|
| 93 |
+
model_config = ConfigDict(extra='allow')
|
| 94 |
+
|
| 95 |
+
name: str
|
| 96 |
+
|
| 97 |
+
user = User(name='John Doe', age=20) # (1)!
|
| 98 |
+
print(user)
|
| 99 |
+
#> name='John Doe' age=20
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
1. The `age` argument is included.
|
| 103 |
+
|
| 104 |
+
With `extra='forbid'`, an error is raised:
|
| 105 |
+
|
| 106 |
+
```python
|
| 107 |
+
from pydantic import BaseModel, ConfigDict, ValidationError
|
| 108 |
+
|
| 109 |
+
class User(BaseModel):
|
| 110 |
+
model_config = ConfigDict(extra='forbid')
|
| 111 |
+
|
| 112 |
+
name: str
|
| 113 |
+
|
| 114 |
+
try:
|
| 115 |
+
User(name='John Doe', age=20)
|
| 116 |
+
except ValidationError as e:
|
| 117 |
+
print(e)
|
| 118 |
+
'''
|
| 119 |
+
1 validation error for User
|
| 120 |
+
age
|
| 121 |
+
Extra inputs are not permitted [type=extra_forbidden, input_value=20, input_type=int]
|
| 122 |
+
'''
|
| 123 |
+
```
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
frozen: bool
|
| 127 |
+
"""
|
| 128 |
+
Whether models are faux-immutable, i.e. whether `__setattr__` is allowed, and also generates
|
| 129 |
+
a `__hash__()` method for the model. This makes instances of the model potentially hashable if all the
|
| 130 |
+
attributes are hashable. Defaults to `False`.
|
| 131 |
+
|
| 132 |
+
Note:
|
| 133 |
+
On V1, the inverse of this setting was called `allow_mutation`, and was `True` by default.
|
| 134 |
+
"""
|
| 135 |
+
|
| 136 |
+
populate_by_name: bool
|
| 137 |
+
"""
|
| 138 |
+
Whether an aliased field may be populated by its name as given by the model
|
| 139 |
+
attribute, as well as the alias. Defaults to `False`.
|
| 140 |
+
|
| 141 |
+
Note:
|
| 142 |
+
The name of this configuration setting was changed in **v2.0** from
|
| 143 |
+
`allow_population_by_field_name` to `populate_by_name`.
|
| 144 |
+
|
| 145 |
+
```python
|
| 146 |
+
from pydantic import BaseModel, ConfigDict, Field
|
| 147 |
+
|
| 148 |
+
class User(BaseModel):
|
| 149 |
+
model_config = ConfigDict(populate_by_name=True)
|
| 150 |
+
|
| 151 |
+
name: str = Field(alias='full_name') # (1)!
|
| 152 |
+
age: int
|
| 153 |
+
|
| 154 |
+
user = User(full_name='John Doe', age=20) # (2)!
|
| 155 |
+
print(user)
|
| 156 |
+
#> name='John Doe' age=20
|
| 157 |
+
user = User(name='John Doe', age=20) # (3)!
|
| 158 |
+
print(user)
|
| 159 |
+
#> name='John Doe' age=20
|
| 160 |
+
```
|
| 161 |
+
|
| 162 |
+
1. The field `'name'` has an alias `'full_name'`.
|
| 163 |
+
2. The model is populated by the alias `'full_name'`.
|
| 164 |
+
3. The model is populated by the field name `'name'`.
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
use_enum_values: bool
|
| 168 |
+
"""
|
| 169 |
+
Whether to populate models with the `value` property of enums, rather than the raw enum.
|
| 170 |
+
This may be useful if you want to serialize `model.model_dump()` later. Defaults to `False`.
|
| 171 |
+
|
| 172 |
+
!!! note
|
| 173 |
+
If you have an `Optional[Enum]` value that you set a default for, you need to use `validate_default=True`
|
| 174 |
+
for said Field to ensure that the `use_enum_values` flag takes effect on the default, as extracting an
|
| 175 |
+
enum's value occurs during validation, not serialization.
|
| 176 |
+
|
| 177 |
+
```python
|
| 178 |
+
from enum import Enum
|
| 179 |
+
from typing import Optional
|
| 180 |
+
|
| 181 |
+
from pydantic import BaseModel, ConfigDict, Field
|
| 182 |
+
|
| 183 |
+
class SomeEnum(Enum):
|
| 184 |
+
FOO = 'foo'
|
| 185 |
+
BAR = 'bar'
|
| 186 |
+
BAZ = 'baz'
|
| 187 |
+
|
| 188 |
+
class SomeModel(BaseModel):
|
| 189 |
+
model_config = ConfigDict(use_enum_values=True)
|
| 190 |
+
|
| 191 |
+
some_enum: SomeEnum
|
| 192 |
+
another_enum: Optional[SomeEnum] = Field(
|
| 193 |
+
default=SomeEnum.FOO, validate_default=True
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
model1 = SomeModel(some_enum=SomeEnum.BAR)
|
| 197 |
+
print(model1.model_dump())
|
| 198 |
+
#> {'some_enum': 'bar', 'another_enum': 'foo'}
|
| 199 |
+
|
| 200 |
+
model2 = SomeModel(some_enum=SomeEnum.BAR, another_enum=SomeEnum.BAZ)
|
| 201 |
+
print(model2.model_dump())
|
| 202 |
+
#> {'some_enum': 'bar', 'another_enum': 'baz'}
|
| 203 |
+
```
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
validate_assignment: bool
|
| 207 |
+
"""
|
| 208 |
+
Whether to validate the data when the model is changed. Defaults to `False`.
|
| 209 |
+
|
| 210 |
+
The default behavior of Pydantic is to validate the data when the model is created.
|
| 211 |
+
|
| 212 |
+
In case the user changes the data after the model is created, the model is _not_ revalidated.
|
| 213 |
+
|
| 214 |
+
```python
|
| 215 |
+
from pydantic import BaseModel
|
| 216 |
+
|
| 217 |
+
class User(BaseModel):
|
| 218 |
+
name: str
|
| 219 |
+
|
| 220 |
+
user = User(name='John Doe') # (1)!
|
| 221 |
+
print(user)
|
| 222 |
+
#> name='John Doe'
|
| 223 |
+
user.name = 123 # (1)!
|
| 224 |
+
print(user)
|
| 225 |
+
#> name=123
|
| 226 |
+
```
|
| 227 |
+
|
| 228 |
+
1. The validation happens only when the model is created.
|
| 229 |
+
2. The validation does not happen when the data is changed.
|
| 230 |
+
|
| 231 |
+
In case you want to revalidate the model when the data is changed, you can use `validate_assignment=True`:
|
| 232 |
+
|
| 233 |
+
```python
|
| 234 |
+
from pydantic import BaseModel, ValidationError
|
| 235 |
+
|
| 236 |
+
class User(BaseModel, validate_assignment=True): # (1)!
|
| 237 |
+
name: str
|
| 238 |
+
|
| 239 |
+
user = User(name='John Doe') # (2)!
|
| 240 |
+
print(user)
|
| 241 |
+
#> name='John Doe'
|
| 242 |
+
try:
|
| 243 |
+
user.name = 123 # (3)!
|
| 244 |
+
except ValidationError as e:
|
| 245 |
+
print(e)
|
| 246 |
+
'''
|
| 247 |
+
1 validation error for User
|
| 248 |
+
name
|
| 249 |
+
Input should be a valid string [type=string_type, input_value=123, input_type=int]
|
| 250 |
+
'''
|
| 251 |
+
```
|
| 252 |
+
|
| 253 |
+
1. You can either use class keyword arguments, or `model_config` to set `validate_assignment=True`.
|
| 254 |
+
2. The validation happens when the model is created.
|
| 255 |
+
3. The validation _also_ happens when the data is changed.
|
| 256 |
+
"""
|
| 257 |
+
|
| 258 |
+
arbitrary_types_allowed: bool
|
| 259 |
+
"""
|
| 260 |
+
Whether arbitrary types are allowed for field types. Defaults to `False`.
|
| 261 |
+
|
| 262 |
+
```python
|
| 263 |
+
from pydantic import BaseModel, ConfigDict, ValidationError
|
| 264 |
+
|
| 265 |
+
# This is not a pydantic model, it's an arbitrary class
|
| 266 |
+
class Pet:
|
| 267 |
+
def __init__(self, name: str):
|
| 268 |
+
self.name = name
|
| 269 |
+
|
| 270 |
+
class Model(BaseModel):
|
| 271 |
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
| 272 |
+
|
| 273 |
+
pet: Pet
|
| 274 |
+
owner: str
|
| 275 |
+
|
| 276 |
+
pet = Pet(name='Hedwig')
|
| 277 |
+
# A simple check of instance type is used to validate the data
|
| 278 |
+
model = Model(owner='Harry', pet=pet)
|
| 279 |
+
print(model)
|
| 280 |
+
#> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
|
| 281 |
+
print(model.pet)
|
| 282 |
+
#> <__main__.Pet object at 0x0123456789ab>
|
| 283 |
+
print(model.pet.name)
|
| 284 |
+
#> Hedwig
|
| 285 |
+
print(type(model.pet))
|
| 286 |
+
#> <class '__main__.Pet'>
|
| 287 |
+
try:
|
| 288 |
+
# If the value is not an instance of the type, it's invalid
|
| 289 |
+
Model(owner='Harry', pet='Hedwig')
|
| 290 |
+
except ValidationError as e:
|
| 291 |
+
print(e)
|
| 292 |
+
'''
|
| 293 |
+
1 validation error for Model
|
| 294 |
+
pet
|
| 295 |
+
Input should be an instance of Pet [type=is_instance_of, input_value='Hedwig', input_type=str]
|
| 296 |
+
'''
|
| 297 |
+
|
| 298 |
+
# Nothing in the instance of the arbitrary type is checked
|
| 299 |
+
# Here name probably should have been a str, but it's not validated
|
| 300 |
+
pet2 = Pet(name=42)
|
| 301 |
+
model2 = Model(owner='Harry', pet=pet2)
|
| 302 |
+
print(model2)
|
| 303 |
+
#> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
|
| 304 |
+
print(model2.pet)
|
| 305 |
+
#> <__main__.Pet object at 0x0123456789ab>
|
| 306 |
+
print(model2.pet.name)
|
| 307 |
+
#> 42
|
| 308 |
+
print(type(model2.pet))
|
| 309 |
+
#> <class '__main__.Pet'>
|
| 310 |
+
```
|
| 311 |
+
"""
|
| 312 |
+
|
| 313 |
+
from_attributes: bool
|
| 314 |
+
"""
|
| 315 |
+
Whether to build models and look up discriminators of tagged unions using python object attributes.
|
| 316 |
+
"""
|
| 317 |
+
|
| 318 |
+
loc_by_alias: bool
|
| 319 |
+
"""Whether to use the actual key provided in the data (e.g. alias) for error `loc`s rather than the field's name. Defaults to `True`."""
|
| 320 |
+
|
| 321 |
+
alias_generator: Callable[[str], str] | AliasGenerator | None
|
| 322 |
+
"""
|
| 323 |
+
A callable that takes a field name and returns an alias for it
|
| 324 |
+
or an instance of [`AliasGenerator`][pydantic.aliases.AliasGenerator]. Defaults to `None`.
|
| 325 |
+
|
| 326 |
+
When using a callable, the alias generator is used for both validation and serialization.
|
| 327 |
+
If you want to use different alias generators for validation and serialization, you can use
|
| 328 |
+
[`AliasGenerator`][pydantic.aliases.AliasGenerator] instead.
|
| 329 |
+
|
| 330 |
+
If data source field names do not match your code style (e. g. CamelCase fields),
|
| 331 |
+
you can automatically generate aliases using `alias_generator`. Here's an example with
|
| 332 |
+
a basic callable:
|
| 333 |
+
|
| 334 |
+
```python
|
| 335 |
+
from pydantic import BaseModel, ConfigDict
|
| 336 |
+
from pydantic.alias_generators import to_pascal
|
| 337 |
+
|
| 338 |
+
class Voice(BaseModel):
|
| 339 |
+
model_config = ConfigDict(alias_generator=to_pascal)
|
| 340 |
+
|
| 341 |
+
name: str
|
| 342 |
+
language_code: str
|
| 343 |
+
|
| 344 |
+
voice = Voice(Name='Filiz', LanguageCode='tr-TR')
|
| 345 |
+
print(voice.language_code)
|
| 346 |
+
#> tr-TR
|
| 347 |
+
print(voice.model_dump(by_alias=True))
|
| 348 |
+
#> {'Name': 'Filiz', 'LanguageCode': 'tr-TR'}
|
| 349 |
+
```
|
| 350 |
+
|
| 351 |
+
If you want to use different alias generators for validation and serialization, you can use
|
| 352 |
+
[`AliasGenerator`][pydantic.aliases.AliasGenerator].
|
| 353 |
+
|
| 354 |
+
```python
|
| 355 |
+
from pydantic import AliasGenerator, BaseModel, ConfigDict
|
| 356 |
+
from pydantic.alias_generators import to_camel, to_pascal
|
| 357 |
+
|
| 358 |
+
class Athlete(BaseModel):
|
| 359 |
+
first_name: str
|
| 360 |
+
last_name: str
|
| 361 |
+
sport: str
|
| 362 |
+
|
| 363 |
+
model_config = ConfigDict(
|
| 364 |
+
alias_generator=AliasGenerator(
|
| 365 |
+
validation_alias=to_camel,
|
| 366 |
+
serialization_alias=to_pascal,
|
| 367 |
+
)
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
athlete = Athlete(firstName='John', lastName='Doe', sport='track')
|
| 371 |
+
print(athlete.model_dump(by_alias=True))
|
| 372 |
+
#> {'FirstName': 'John', 'LastName': 'Doe', 'Sport': 'track'}
|
| 373 |
+
```
|
| 374 |
+
|
| 375 |
+
Note:
|
| 376 |
+
Pydantic offers three built-in alias generators: [`to_pascal`][pydantic.alias_generators.to_pascal],
|
| 377 |
+
[`to_camel`][pydantic.alias_generators.to_camel], and [`to_snake`][pydantic.alias_generators.to_snake].
|
| 378 |
+
"""
|
| 379 |
+
|
| 380 |
+
ignored_types: tuple[type, ...]
|
| 381 |
+
"""A tuple of types that may occur as values of class attributes without annotations. This is
|
| 382 |
+
typically used for custom descriptors (classes that behave like `property`). If an attribute is set on a
|
| 383 |
+
class without an annotation and has a type that is not in this tuple (or otherwise recognized by
|
| 384 |
+
_pydantic_), an error will be raised. Defaults to `()`.
|
| 385 |
+
"""
|
| 386 |
+
|
| 387 |
+
allow_inf_nan: bool
|
| 388 |
+
"""Whether to allow infinity (`+inf` an `-inf`) and NaN values to float and decimal fields. Defaults to `True`."""
|
| 389 |
+
|
| 390 |
+
json_schema_extra: JsonDict | JsonSchemaExtraCallable | None
|
| 391 |
+
"""A dict or callable to provide extra JSON schema properties. Defaults to `None`."""
|
| 392 |
+
|
| 393 |
+
json_encoders: dict[type[object], JsonEncoder] | None
|
| 394 |
+
"""
|
| 395 |
+
A `dict` of custom JSON encoders for specific types. Defaults to `None`.
|
| 396 |
+
|
| 397 |
+
!!! warning "Deprecated"
|
| 398 |
+
This config option is a carryover from v1.
|
| 399 |
+
We originally planned to remove it in v2 but didn't have a 1:1 replacement so we are keeping it for now.
|
| 400 |
+
It is still deprecated and will likely be removed in the future.
|
| 401 |
+
"""
|
| 402 |
+
|
| 403 |
+
# new in V2
|
| 404 |
+
strict: bool
|
| 405 |
+
"""
|
| 406 |
+
_(new in V2)_ If `True`, strict validation is applied to all fields on the model.
|
| 407 |
+
|
| 408 |
+
By default, Pydantic attempts to coerce values to the correct type, when possible.
|
| 409 |
+
|
| 410 |
+
There are situations in which you may want to disable this behavior, and instead raise an error if a value's type
|
| 411 |
+
does not match the field's type annotation.
|
| 412 |
+
|
| 413 |
+
To configure strict mode for all fields on a model, you can set `strict=True` on the model.
|
| 414 |
+
|
| 415 |
+
```python
|
| 416 |
+
from pydantic import BaseModel, ConfigDict
|
| 417 |
+
|
| 418 |
+
class Model(BaseModel):
|
| 419 |
+
model_config = ConfigDict(strict=True)
|
| 420 |
+
|
| 421 |
+
name: str
|
| 422 |
+
age: int
|
| 423 |
+
```
|
| 424 |
+
|
| 425 |
+
See [Strict Mode](../concepts/strict_mode.md) for more details.
|
| 426 |
+
|
| 427 |
+
See the [Conversion Table](../concepts/conversion_table.md) for more details on how Pydantic converts data in both
|
| 428 |
+
strict and lax modes.
|
| 429 |
+
"""
|
| 430 |
+
# whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never'
|
| 431 |
+
revalidate_instances: Literal['always', 'never', 'subclass-instances']
|
| 432 |
+
"""
|
| 433 |
+
When and how to revalidate models and dataclasses during validation. Accepts the string
|
| 434 |
+
values of `'never'`, `'always'` and `'subclass-instances'`. Defaults to `'never'`.
|
| 435 |
+
|
| 436 |
+
- `'never'` will not revalidate models and dataclasses during validation
|
| 437 |
+
- `'always'` will revalidate models and dataclasses during validation
|
| 438 |
+
- `'subclass-instances'` will revalidate models and dataclasses during validation if the instance is a
|
| 439 |
+
subclass of the model or dataclass
|
| 440 |
+
|
| 441 |
+
By default, model and dataclass instances are not revalidated during validation.
|
| 442 |
+
|
| 443 |
+
```python
|
| 444 |
+
from typing import List
|
| 445 |
+
|
| 446 |
+
from pydantic import BaseModel
|
| 447 |
+
|
| 448 |
+
class User(BaseModel, revalidate_instances='never'): # (1)!
|
| 449 |
+
hobbies: List[str]
|
| 450 |
+
|
| 451 |
+
class SubUser(User):
|
| 452 |
+
sins: List[str]
|
| 453 |
+
|
| 454 |
+
class Transaction(BaseModel):
|
| 455 |
+
user: User
|
| 456 |
+
|
| 457 |
+
my_user = User(hobbies=['reading'])
|
| 458 |
+
t = Transaction(user=my_user)
|
| 459 |
+
print(t)
|
| 460 |
+
#> user=User(hobbies=['reading'])
|
| 461 |
+
|
| 462 |
+
my_user.hobbies = [1] # (2)!
|
| 463 |
+
t = Transaction(user=my_user) # (3)!
|
| 464 |
+
print(t)
|
| 465 |
+
#> user=User(hobbies=[1])
|
| 466 |
+
|
| 467 |
+
my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
|
| 468 |
+
t = Transaction(user=my_sub_user)
|
| 469 |
+
print(t)
|
| 470 |
+
#> user=SubUser(hobbies=['scuba diving'], sins=['lying'])
|
| 471 |
+
```
|
| 472 |
+
|
| 473 |
+
1. `revalidate_instances` is set to `'never'` by **default.
|
| 474 |
+
2. The assignment is not validated, unless you set `validate_assignment` to `True` in the model's config.
|
| 475 |
+
3. Since `revalidate_instances` is set to `never`, this is not revalidated.
|
| 476 |
+
|
| 477 |
+
If you want to revalidate instances during validation, you can set `revalidate_instances` to `'always'`
|
| 478 |
+
in the model's config.
|
| 479 |
+
|
| 480 |
+
```python
|
| 481 |
+
from typing import List
|
| 482 |
+
|
| 483 |
+
from pydantic import BaseModel, ValidationError
|
| 484 |
+
|
| 485 |
+
class User(BaseModel, revalidate_instances='always'): # (1)!
|
| 486 |
+
hobbies: List[str]
|
| 487 |
+
|
| 488 |
+
class SubUser(User):
|
| 489 |
+
sins: List[str]
|
| 490 |
+
|
| 491 |
+
class Transaction(BaseModel):
|
| 492 |
+
user: User
|
| 493 |
+
|
| 494 |
+
my_user = User(hobbies=['reading'])
|
| 495 |
+
t = Transaction(user=my_user)
|
| 496 |
+
print(t)
|
| 497 |
+
#> user=User(hobbies=['reading'])
|
| 498 |
+
|
| 499 |
+
my_user.hobbies = [1]
|
| 500 |
+
try:
|
| 501 |
+
t = Transaction(user=my_user) # (2)!
|
| 502 |
+
except ValidationError as e:
|
| 503 |
+
print(e)
|
| 504 |
+
'''
|
| 505 |
+
1 validation error for Transaction
|
| 506 |
+
user.hobbies.0
|
| 507 |
+
Input should be a valid string [type=string_type, input_value=1, input_type=int]
|
| 508 |
+
'''
|
| 509 |
+
|
| 510 |
+
my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
|
| 511 |
+
t = Transaction(user=my_sub_user)
|
| 512 |
+
print(t) # (3)!
|
| 513 |
+
#> user=User(hobbies=['scuba diving'])
|
| 514 |
+
```
|
| 515 |
+
|
| 516 |
+
1. `revalidate_instances` is set to `'always'`.
|
| 517 |
+
2. The model is revalidated, since `revalidate_instances` is set to `'always'`.
|
| 518 |
+
3. Using `'never'` we would have gotten `user=SubUser(hobbies=['scuba diving'], sins=['lying'])`.
|
| 519 |
+
|
| 520 |
+
It's also possible to set `revalidate_instances` to `'subclass-instances'` to only revalidate instances
|
| 521 |
+
of subclasses of the model.
|
| 522 |
+
|
| 523 |
+
```python
|
| 524 |
+
from typing import List
|
| 525 |
+
|
| 526 |
+
from pydantic import BaseModel
|
| 527 |
+
|
| 528 |
+
class User(BaseModel, revalidate_instances='subclass-instances'): # (1)!
|
| 529 |
+
hobbies: List[str]
|
| 530 |
+
|
| 531 |
+
class SubUser(User):
|
| 532 |
+
sins: List[str]
|
| 533 |
+
|
| 534 |
+
class Transaction(BaseModel):
|
| 535 |
+
user: User
|
| 536 |
+
|
| 537 |
+
my_user = User(hobbies=['reading'])
|
| 538 |
+
t = Transaction(user=my_user)
|
| 539 |
+
print(t)
|
| 540 |
+
#> user=User(hobbies=['reading'])
|
| 541 |
+
|
| 542 |
+
my_user.hobbies = [1]
|
| 543 |
+
t = Transaction(user=my_user) # (2)!
|
| 544 |
+
print(t)
|
| 545 |
+
#> user=User(hobbies=[1])
|
| 546 |
+
|
| 547 |
+
my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
|
| 548 |
+
t = Transaction(user=my_sub_user)
|
| 549 |
+
print(t) # (3)!
|
| 550 |
+
#> user=User(hobbies=['scuba diving'])
|
| 551 |
+
```
|
| 552 |
+
|
| 553 |
+
1. `revalidate_instances` is set to `'subclass-instances'`.
|
| 554 |
+
2. This is not revalidated, since `my_user` is not a subclass of `User`.
|
| 555 |
+
3. Using `'never'` we would have gotten `user=SubUser(hobbies=['scuba diving'], sins=['lying'])`.
|
| 556 |
+
"""
|
| 557 |
+
|
| 558 |
+
ser_json_timedelta: Literal['iso8601', 'float']
|
| 559 |
+
"""
|
| 560 |
+
The format of JSON serialized timedeltas. Accepts the string values of `'iso8601'` and
|
| 561 |
+
`'float'`. Defaults to `'iso8601'`.
|
| 562 |
+
|
| 563 |
+
- `'iso8601'` will serialize timedeltas to ISO 8601 durations.
|
| 564 |
+
- `'float'` will serialize timedeltas to the total number of seconds.
|
| 565 |
+
"""
|
| 566 |
+
|
| 567 |
+
ser_json_bytes: Literal['utf8', 'base64', 'hex']
|
| 568 |
+
"""
|
| 569 |
+
The encoding of JSON serialized bytes. Defaults to `'utf8'`.
|
| 570 |
+
Set equal to `val_json_bytes` to get back an equal value after serialization round trip.
|
| 571 |
+
|
| 572 |
+
- `'utf8'` will serialize bytes to UTF-8 strings.
|
| 573 |
+
- `'base64'` will serialize bytes to URL safe base64 strings.
|
| 574 |
+
- `'hex'` will serialize bytes to hexadecimal strings.
|
| 575 |
+
"""
|
| 576 |
+
|
| 577 |
+
val_json_bytes: Literal['utf8', 'base64', 'hex']
|
| 578 |
+
"""
|
| 579 |
+
The encoding of JSON serialized bytes to decode. Defaults to `'utf8'`.
|
| 580 |
+
Set equal to `ser_json_bytes` to get back an equal value after serialization round trip.
|
| 581 |
+
|
| 582 |
+
- `'utf8'` will deserialize UTF-8 strings to bytes.
|
| 583 |
+
- `'base64'` will deserialize URL safe base64 strings to bytes.
|
| 584 |
+
- `'hex'` will deserialize hexadecimal strings to bytes.
|
| 585 |
+
"""
|
| 586 |
+
|
| 587 |
+
ser_json_inf_nan: Literal['null', 'constants', 'strings']
|
| 588 |
+
"""
|
| 589 |
+
The encoding of JSON serialized infinity and NaN float values. Defaults to `'null'`.
|
| 590 |
+
|
| 591 |
+
- `'null'` will serialize infinity and NaN values as `null`.
|
| 592 |
+
- `'constants'` will serialize infinity and NaN values as `Infinity` and `NaN`.
|
| 593 |
+
- `'strings'` will serialize infinity as string `"Infinity"` and NaN as string `"NaN"`.
|
| 594 |
+
"""
|
| 595 |
+
|
| 596 |
+
# whether to validate default values during validation, default False
|
| 597 |
+
validate_default: bool
|
| 598 |
+
"""Whether to validate default values during validation. Defaults to `False`."""
|
| 599 |
+
|
| 600 |
+
validate_return: bool
|
| 601 |
+
"""Whether to validate the return value from call validators. Defaults to `False`."""
|
| 602 |
+
|
| 603 |
+
protected_namespaces: tuple[str | Pattern[str], ...]
|
| 604 |
+
"""
|
| 605 |
+
A `tuple` of strings and/or patterns that prevent models from having fields with names that conflict with them.
|
| 606 |
+
For strings, we match on a prefix basis. Ex, if 'dog' is in the protected namespace, 'dog_name' will be protected.
|
| 607 |
+
For patterns, we match on the entire field name. Ex, if `re.compile(r'^dog$')` is in the protected namespace, 'dog' will be protected, but 'dog_name' will not be.
|
| 608 |
+
Defaults to `('model_validate', 'model_dump',)`.
|
| 609 |
+
|
| 610 |
+
The reason we've selected these is to prevent collisions with other validation / dumping formats
|
| 611 |
+
in the future - ex, `model_validate_{some_newly_supported_format}`.
|
| 612 |
+
|
| 613 |
+
Before v2.10, Pydantic used `('model_',)` as the default value for this setting to
|
| 614 |
+
prevent collisions between model attributes and `BaseModel`'s own methods. This was changed
|
| 615 |
+
in v2.10 given feedback that this restriction was limiting in AI and data science contexts,
|
| 616 |
+
where it is common to have fields with names like `model_id`, `model_input`, `model_output`, etc.
|
| 617 |
+
|
| 618 |
+
For more details, see https://github.com/pydantic/pydantic/issues/10315.
|
| 619 |
+
|
| 620 |
+
```python
|
| 621 |
+
import warnings
|
| 622 |
+
|
| 623 |
+
from pydantic import BaseModel
|
| 624 |
+
|
| 625 |
+
warnings.filterwarnings('error') # Raise warnings as errors
|
| 626 |
+
|
| 627 |
+
try:
|
| 628 |
+
|
| 629 |
+
class Model(BaseModel):
|
| 630 |
+
model_dump_something: str
|
| 631 |
+
|
| 632 |
+
except UserWarning as e:
|
| 633 |
+
print(e)
|
| 634 |
+
'''
|
| 635 |
+
Field "model_dump_something" in Model has conflict with protected namespace "model_dump".
|
| 636 |
+
|
| 637 |
+
You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('model_validate',)`.
|
| 638 |
+
'''
|
| 639 |
+
```
|
| 640 |
+
|
| 641 |
+
You can customize this behavior using the `protected_namespaces` setting:
|
| 642 |
+
|
| 643 |
+
```python {test="skip"}
|
| 644 |
+
import re
|
| 645 |
+
import warnings
|
| 646 |
+
|
| 647 |
+
from pydantic import BaseModel, ConfigDict
|
| 648 |
+
|
| 649 |
+
with warnings.catch_warnings(record=True) as caught_warnings:
|
| 650 |
+
warnings.simplefilter('always') # Catch all warnings
|
| 651 |
+
|
| 652 |
+
class Model(BaseModel):
|
| 653 |
+
safe_field: str
|
| 654 |
+
also_protect_field: str
|
| 655 |
+
protect_this: str
|
| 656 |
+
|
| 657 |
+
model_config = ConfigDict(
|
| 658 |
+
protected_namespaces=(
|
| 659 |
+
'protect_me_',
|
| 660 |
+
'also_protect_',
|
| 661 |
+
re.compile('^protect_this$'),
|
| 662 |
+
)
|
| 663 |
+
)
|
| 664 |
+
|
| 665 |
+
for warning in caught_warnings:
|
| 666 |
+
print(f'{warning.message}')
|
| 667 |
+
'''
|
| 668 |
+
Field "also_protect_field" in Model has conflict with protected namespace "also_protect_".
|
| 669 |
+
You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('protect_me_', re.compile('^protect_this$'))`.
|
| 670 |
+
|
| 671 |
+
Field "protect_this" in Model has conflict with protected namespace "re.compile('^protect_this$')".
|
| 672 |
+
You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('protect_me_', 'also_protect_')`.
|
| 673 |
+
'''
|
| 674 |
+
```
|
| 675 |
+
|
| 676 |
+
While Pydantic will only emit a warning when an item is in a protected namespace but does not actually have a collision,
|
| 677 |
+
an error _is_ raised if there is an actual collision with an existing attribute:
|
| 678 |
+
|
| 679 |
+
```python
|
| 680 |
+
from pydantic import BaseModel, ConfigDict
|
| 681 |
+
|
| 682 |
+
try:
|
| 683 |
+
|
| 684 |
+
class Model(BaseModel):
|
| 685 |
+
model_validate: str
|
| 686 |
+
|
| 687 |
+
model_config = ConfigDict(protected_namespaces=('model_',))
|
| 688 |
+
|
| 689 |
+
except NameError as e:
|
| 690 |
+
print(e)
|
| 691 |
+
'''
|
| 692 |
+
Field "model_validate" conflicts with member <bound method BaseModel.model_validate of <class 'pydantic.main.BaseModel'>> of protected namespace "model_".
|
| 693 |
+
'''
|
| 694 |
+
```
|
| 695 |
+
"""
|
| 696 |
+
|
| 697 |
+
hide_input_in_errors: bool
|
| 698 |
+
"""
|
| 699 |
+
Whether to hide inputs when printing errors. Defaults to `False`.
|
| 700 |
+
|
| 701 |
+
Pydantic shows the input value and type when it raises `ValidationError` during the validation.
|
| 702 |
+
|
| 703 |
+
```python
|
| 704 |
+
from pydantic import BaseModel, ValidationError
|
| 705 |
+
|
| 706 |
+
class Model(BaseModel):
|
| 707 |
+
a: str
|
| 708 |
+
|
| 709 |
+
try:
|
| 710 |
+
Model(a=123)
|
| 711 |
+
except ValidationError as e:
|
| 712 |
+
print(e)
|
| 713 |
+
'''
|
| 714 |
+
1 validation error for Model
|
| 715 |
+
a
|
| 716 |
+
Input should be a valid string [type=string_type, input_value=123, input_type=int]
|
| 717 |
+
'''
|
| 718 |
+
```
|
| 719 |
+
|
| 720 |
+
You can hide the input value and type by setting the `hide_input_in_errors` config to `True`.
|
| 721 |
+
|
| 722 |
+
```python
|
| 723 |
+
from pydantic import BaseModel, ConfigDict, ValidationError
|
| 724 |
+
|
| 725 |
+
class Model(BaseModel):
|
| 726 |
+
a: str
|
| 727 |
+
model_config = ConfigDict(hide_input_in_errors=True)
|
| 728 |
+
|
| 729 |
+
try:
|
| 730 |
+
Model(a=123)
|
| 731 |
+
except ValidationError as e:
|
| 732 |
+
print(e)
|
| 733 |
+
'''
|
| 734 |
+
1 validation error for Model
|
| 735 |
+
a
|
| 736 |
+
Input should be a valid string [type=string_type]
|
| 737 |
+
'''
|
| 738 |
+
```
|
| 739 |
+
"""
|
| 740 |
+
|
| 741 |
+
defer_build: bool
|
| 742 |
+
"""
|
| 743 |
+
Whether to defer model validator and serializer construction until the first model validation. Defaults to False.
|
| 744 |
+
|
| 745 |
+
This can be useful to avoid the overhead of building models which are only
|
| 746 |
+
used nested within other models, or when you want to manually define type namespace via
|
| 747 |
+
[`Model.model_rebuild(_types_namespace=...)`][pydantic.BaseModel.model_rebuild].
|
| 748 |
+
|
| 749 |
+
Since v2.10, this setting also applies to pydantic dataclasses and TypeAdapter instances.
|
| 750 |
+
"""
|
| 751 |
+
|
| 752 |
+
plugin_settings: dict[str, object] | None
|
| 753 |
+
"""A `dict` of settings for plugins. Defaults to `None`."""
|
| 754 |
+
|
| 755 |
+
schema_generator: type[_GenerateSchema] | None
|
| 756 |
+
"""
|
| 757 |
+
!!! warning
|
| 758 |
+
`schema_generator` is deprecated in v2.10.
|
| 759 |
+
|
| 760 |
+
Prior to v2.10, this setting was advertised as highly subject to change.
|
| 761 |
+
It's possible that this interface may once again become public once the internal core schema generation
|
| 762 |
+
API is more stable, but that will likely come after significant performance improvements have been made.
|
| 763 |
+
"""
|
| 764 |
+
|
| 765 |
+
json_schema_serialization_defaults_required: bool
|
| 766 |
+
"""
|
| 767 |
+
Whether fields with default values should be marked as required in the serialization schema. Defaults to `False`.
|
| 768 |
+
|
| 769 |
+
This ensures that the serialization schema will reflect the fact a field with a default will always be present
|
| 770 |
+
when serializing the model, even though it is not required for validation.
|
| 771 |
+
|
| 772 |
+
However, there are scenarios where this may be undesirable — in particular, if you want to share the schema
|
| 773 |
+
between validation and serialization, and don't mind fields with defaults being marked as not required during
|
| 774 |
+
serialization. See [#7209](https://github.com/pydantic/pydantic/issues/7209) for more details.
|
| 775 |
+
|
| 776 |
+
```python
|
| 777 |
+
from pydantic import BaseModel, ConfigDict
|
| 778 |
+
|
| 779 |
+
class Model(BaseModel):
|
| 780 |
+
a: str = 'a'
|
| 781 |
+
|
| 782 |
+
model_config = ConfigDict(json_schema_serialization_defaults_required=True)
|
| 783 |
+
|
| 784 |
+
print(Model.model_json_schema(mode='validation'))
|
| 785 |
+
'''
|
| 786 |
+
{
|
| 787 |
+
'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
|
| 788 |
+
'title': 'Model',
|
| 789 |
+
'type': 'object',
|
| 790 |
+
}
|
| 791 |
+
'''
|
| 792 |
+
print(Model.model_json_schema(mode='serialization'))
|
| 793 |
+
'''
|
| 794 |
+
{
|
| 795 |
+
'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
|
| 796 |
+
'required': ['a'],
|
| 797 |
+
'title': 'Model',
|
| 798 |
+
'type': 'object',
|
| 799 |
+
}
|
| 800 |
+
'''
|
| 801 |
+
```
|
| 802 |
+
"""
|
| 803 |
+
|
| 804 |
+
json_schema_mode_override: Literal['validation', 'serialization', None]
|
| 805 |
+
"""
|
| 806 |
+
If not `None`, the specified mode will be used to generate the JSON schema regardless of what `mode` was passed to
|
| 807 |
+
the function call. Defaults to `None`.
|
| 808 |
+
|
| 809 |
+
This provides a way to force the JSON schema generation to reflect a specific mode, e.g., to always use the
|
| 810 |
+
validation schema.
|
| 811 |
+
|
| 812 |
+
It can be useful when using frameworks (such as FastAPI) that may generate different schemas for validation
|
| 813 |
+
and serialization that must both be referenced from the same schema; when this happens, we automatically append
|
| 814 |
+
`-Input` to the definition reference for the validation schema and `-Output` to the definition reference for the
|
| 815 |
+
serialization schema. By specifying a `json_schema_mode_override` though, this prevents the conflict between
|
| 816 |
+
the validation and serialization schemas (since both will use the specified schema), and so prevents the suffixes
|
| 817 |
+
from being added to the definition references.
|
| 818 |
+
|
| 819 |
+
```python
|
| 820 |
+
from pydantic import BaseModel, ConfigDict, Json
|
| 821 |
+
|
| 822 |
+
class Model(BaseModel):
|
| 823 |
+
a: Json[int] # requires a string to validate, but will dump an int
|
| 824 |
+
|
| 825 |
+
print(Model.model_json_schema(mode='serialization'))
|
| 826 |
+
'''
|
| 827 |
+
{
|
| 828 |
+
'properties': {'a': {'title': 'A', 'type': 'integer'}},
|
| 829 |
+
'required': ['a'],
|
| 830 |
+
'title': 'Model',
|
| 831 |
+
'type': 'object',
|
| 832 |
+
}
|
| 833 |
+
'''
|
| 834 |
+
|
| 835 |
+
class ForceInputModel(Model):
|
| 836 |
+
# the following ensures that even with mode='serialization', we
|
| 837 |
+
# will get the schema that would be generated for validation.
|
| 838 |
+
model_config = ConfigDict(json_schema_mode_override='validation')
|
| 839 |
+
|
| 840 |
+
print(ForceInputModel.model_json_schema(mode='serialization'))
|
| 841 |
+
'''
|
| 842 |
+
{
|
| 843 |
+
'properties': {
|
| 844 |
+
'a': {
|
| 845 |
+
'contentMediaType': 'application/json',
|
| 846 |
+
'contentSchema': {'type': 'integer'},
|
| 847 |
+
'title': 'A',
|
| 848 |
+
'type': 'string',
|
| 849 |
+
}
|
| 850 |
+
},
|
| 851 |
+
'required': ['a'],
|
| 852 |
+
'title': 'ForceInputModel',
|
| 853 |
+
'type': 'object',
|
| 854 |
+
}
|
| 855 |
+
'''
|
| 856 |
+
```
|
| 857 |
+
"""
|
| 858 |
+
|
| 859 |
+
coerce_numbers_to_str: bool
|
| 860 |
+
"""
|
| 861 |
+
If `True`, enables automatic coercion of any `Number` type to `str` in "lax" (non-strict) mode. Defaults to `False`.
|
| 862 |
+
|
| 863 |
+
Pydantic doesn't allow number types (`int`, `float`, `Decimal`) to be coerced as type `str` by default.
|
| 864 |
+
|
| 865 |
+
```python
|
| 866 |
+
from decimal import Decimal
|
| 867 |
+
|
| 868 |
+
from pydantic import BaseModel, ConfigDict, ValidationError
|
| 869 |
+
|
| 870 |
+
class Model(BaseModel):
|
| 871 |
+
value: str
|
| 872 |
+
|
| 873 |
+
try:
|
| 874 |
+
print(Model(value=42))
|
| 875 |
+
except ValidationError as e:
|
| 876 |
+
print(e)
|
| 877 |
+
'''
|
| 878 |
+
1 validation error for Model
|
| 879 |
+
value
|
| 880 |
+
Input should be a valid string [type=string_type, input_value=42, input_type=int]
|
| 881 |
+
'''
|
| 882 |
+
|
| 883 |
+
class Model(BaseModel):
|
| 884 |
+
model_config = ConfigDict(coerce_numbers_to_str=True)
|
| 885 |
+
|
| 886 |
+
value: str
|
| 887 |
+
|
| 888 |
+
repr(Model(value=42).value)
|
| 889 |
+
#> "42"
|
| 890 |
+
repr(Model(value=42.13).value)
|
| 891 |
+
#> "42.13"
|
| 892 |
+
repr(Model(value=Decimal('42.13')).value)
|
| 893 |
+
#> "42.13"
|
| 894 |
+
```
|
| 895 |
+
"""
|
| 896 |
+
|
| 897 |
+
regex_engine: Literal['rust-regex', 'python-re']
|
| 898 |
+
"""
|
| 899 |
+
The regex engine to be used for pattern validation.
|
| 900 |
+
Defaults to `'rust-regex'`.
|
| 901 |
+
|
| 902 |
+
- `rust-regex` uses the [`regex`](https://docs.rs/regex) Rust crate,
|
| 903 |
+
which is non-backtracking and therefore more DDoS resistant, but does not support all regex features.
|
| 904 |
+
- `python-re` use the [`re`](https://docs.python.org/3/library/re.html) module,
|
| 905 |
+
which supports all regex features, but may be slower.
|
| 906 |
+
|
| 907 |
+
!!! note
|
| 908 |
+
If you use a compiled regex pattern, the python-re engine will be used regardless of this setting.
|
| 909 |
+
This is so that flags such as `re.IGNORECASE` are respected.
|
| 910 |
+
|
| 911 |
+
```python
|
| 912 |
+
from pydantic import BaseModel, ConfigDict, Field, ValidationError
|
| 913 |
+
|
| 914 |
+
class Model(BaseModel):
|
| 915 |
+
model_config = ConfigDict(regex_engine='python-re')
|
| 916 |
+
|
| 917 |
+
value: str = Field(pattern=r'^abc(?=def)')
|
| 918 |
+
|
| 919 |
+
print(Model(value='abcdef').value)
|
| 920 |
+
#> abcdef
|
| 921 |
+
|
| 922 |
+
try:
|
| 923 |
+
print(Model(value='abxyzcdef'))
|
| 924 |
+
except ValidationError as e:
|
| 925 |
+
print(e)
|
| 926 |
+
'''
|
| 927 |
+
1 validation error for Model
|
| 928 |
+
value
|
| 929 |
+
String should match pattern '^abc(?=def)' [type=string_pattern_mismatch, input_value='abxyzcdef', input_type=str]
|
| 930 |
+
'''
|
| 931 |
+
```
|
| 932 |
+
"""
|
| 933 |
+
|
| 934 |
+
validation_error_cause: bool
|
| 935 |
+
"""
|
| 936 |
+
If `True`, Python exceptions that were part of a validation failure will be shown as an exception group as a cause. Can be useful for debugging. Defaults to `False`.
|
| 937 |
+
|
| 938 |
+
Note:
|
| 939 |
+
Python 3.10 and older don't support exception groups natively. <=3.10, backport must be installed: `pip install exceptiongroup`.
|
| 940 |
+
|
| 941 |
+
Note:
|
| 942 |
+
The structure of validation errors are likely to change in future Pydantic versions. Pydantic offers no guarantees about their structure. Should be used for visual traceback debugging only.
|
| 943 |
+
"""
|
| 944 |
+
|
| 945 |
+
use_attribute_docstrings: bool
|
| 946 |
+
'''
|
| 947 |
+
Whether docstrings of attributes (bare string literals immediately following the attribute declaration)
|
| 948 |
+
should be used for field descriptions. Defaults to `False`.
|
| 949 |
+
|
| 950 |
+
Available in Pydantic v2.7+.
|
| 951 |
+
|
| 952 |
+
```python
|
| 953 |
+
from pydantic import BaseModel, ConfigDict, Field
|
| 954 |
+
|
| 955 |
+
|
| 956 |
+
class Model(BaseModel):
|
| 957 |
+
model_config = ConfigDict(use_attribute_docstrings=True)
|
| 958 |
+
|
| 959 |
+
x: str
|
| 960 |
+
"""
|
| 961 |
+
Example of an attribute docstring
|
| 962 |
+
"""
|
| 963 |
+
|
| 964 |
+
y: int = Field(description="Description in Field")
|
| 965 |
+
"""
|
| 966 |
+
Description in Field overrides attribute docstring
|
| 967 |
+
"""
|
| 968 |
+
|
| 969 |
+
|
| 970 |
+
print(Model.model_fields["x"].description)
|
| 971 |
+
# > Example of an attribute docstring
|
| 972 |
+
print(Model.model_fields["y"].description)
|
| 973 |
+
# > Description in Field
|
| 974 |
+
```
|
| 975 |
+
This requires the source code of the class to be available at runtime.
|
| 976 |
+
|
| 977 |
+
!!! warning "Usage with `TypedDict`"
|
| 978 |
+
Due to current limitations, attribute docstrings detection may not work as expected when using `TypedDict`
|
| 979 |
+
(in particular when multiple `TypedDict` classes have the same name in the same source file). The behavior
|
| 980 |
+
can be different depending on the Python version used.
|
| 981 |
+
'''
|
| 982 |
+
|
| 983 |
+
cache_strings: bool | Literal['all', 'keys', 'none']
|
| 984 |
+
"""
|
| 985 |
+
Whether to cache strings to avoid constructing new Python objects. Defaults to True.
|
| 986 |
+
|
| 987 |
+
Enabling this setting should significantly improve validation performance while increasing memory usage slightly.
|
| 988 |
+
|
| 989 |
+
- `True` or `'all'` (the default): cache all strings
|
| 990 |
+
- `'keys'`: cache only dictionary keys
|
| 991 |
+
- `False` or `'none'`: no caching
|
| 992 |
+
|
| 993 |
+
!!! note
|
| 994 |
+
`True` or `'all'` is required to cache strings during general validation because
|
| 995 |
+
validators don't know if they're in a key or a value.
|
| 996 |
+
|
| 997 |
+
!!! tip
|
| 998 |
+
If repeated strings are rare, it's recommended to use `'keys'` or `'none'` to reduce memory usage,
|
| 999 |
+
as the performance difference is minimal if repeated strings are rare.
|
| 1000 |
+
"""
|
| 1001 |
+
|
| 1002 |
+
|
| 1003 |
+
_TypeT = TypeVar('_TypeT', bound=type)
|
| 1004 |
+
|
| 1005 |
+
|
| 1006 |
+
def with_config(config: ConfigDict) -> Callable[[_TypeT], _TypeT]:
|
| 1007 |
+
"""Usage docs: https://docs.pydantic.dev/2.10/concepts/config/#configuration-with-dataclass-from-the-standard-library-or-typeddict
|
| 1008 |
+
|
| 1009 |
+
A convenience decorator to set a [Pydantic configuration](config.md) on a `TypedDict` or a `dataclass` from the standard library.
|
| 1010 |
+
|
| 1011 |
+
Although the configuration can be set using the `__pydantic_config__` attribute, it does not play well with type checkers,
|
| 1012 |
+
especially with `TypedDict`.
|
| 1013 |
+
|
| 1014 |
+
!!! example "Usage"
|
| 1015 |
+
|
| 1016 |
+
```python
|
| 1017 |
+
from typing_extensions import TypedDict
|
| 1018 |
+
|
| 1019 |
+
from pydantic import ConfigDict, TypeAdapter, with_config
|
| 1020 |
+
|
| 1021 |
+
@with_config(ConfigDict(str_to_lower=True))
|
| 1022 |
+
class Model(TypedDict):
|
| 1023 |
+
x: str
|
| 1024 |
+
|
| 1025 |
+
ta = TypeAdapter(Model)
|
| 1026 |
+
|
| 1027 |
+
print(ta.validate_python({'x': 'ABC'}))
|
| 1028 |
+
#> {'x': 'abc'}
|
| 1029 |
+
```
|
| 1030 |
+
"""
|
| 1031 |
+
|
| 1032 |
+
def inner(class_: _TypeT, /) -> _TypeT:
|
| 1033 |
+
# Ideally, we would check for `class_` to either be a `TypedDict` or a stdlib dataclass.
|
| 1034 |
+
# However, the `@with_config` decorator can be applied *after* `@dataclass`. To avoid
|
| 1035 |
+
# common mistakes, we at least check for `class_` to not be a Pydantic model.
|
| 1036 |
+
from ._internal._utils import is_model_class
|
| 1037 |
+
|
| 1038 |
+
if is_model_class(class_):
|
| 1039 |
+
raise PydanticUserError(
|
| 1040 |
+
f'Cannot use `with_config` on {class_.__name__} as it is a Pydantic model',
|
| 1041 |
+
code='with-config-on-model',
|
| 1042 |
+
)
|
| 1043 |
+
class_.__pydantic_config__ = config
|
| 1044 |
+
return class_
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Provide an enhanced dataclass that performs validation."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations as _annotations
|
| 4 |
+
|
| 5 |
+
import dataclasses
|
| 6 |
+
import sys
|
| 7 |
+
import types
|
| 8 |
+
from typing import TYPE_CHECKING, Any, Callable, Generic, NoReturn, TypeVar, overload
|
| 9 |
+
from warnings import warn
|
| 10 |
+
|
| 11 |
+
from typing_extensions import Literal, TypeGuard, dataclass_transform
|
| 12 |
+
|
| 13 |
+
from ._internal import _config, _decorators, _namespace_utils, _typing_extra
|
| 14 |
+
from ._internal import _dataclasses as _pydantic_dataclasses
|
| 15 |
+
from ._migration import getattr_migration
|
| 16 |
+
from .config import ConfigDict
|
| 17 |
+
from .errors import PydanticUserError
|
| 18 |
+
from .fields import Field, FieldInfo, PrivateAttr
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from ._internal._dataclasses import PydanticDataclass
|
| 22 |
+
from ._internal._namespace_utils import MappingNamespace
|
| 23 |
+
|
| 24 |
+
__all__ = 'dataclass', 'rebuild_dataclass'
|
| 25 |
+
|
| 26 |
+
_T = TypeVar('_T')
|
| 27 |
+
|
| 28 |
+
if sys.version_info >= (3, 10):
|
| 29 |
+
|
| 30 |
+
@dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr))
|
| 31 |
+
@overload
|
| 32 |
+
def dataclass(
|
| 33 |
+
*,
|
| 34 |
+
init: Literal[False] = False,
|
| 35 |
+
repr: bool = True,
|
| 36 |
+
eq: bool = True,
|
| 37 |
+
order: bool = False,
|
| 38 |
+
unsafe_hash: bool = False,
|
| 39 |
+
frozen: bool = False,
|
| 40 |
+
config: ConfigDict | type[object] | None = None,
|
| 41 |
+
validate_on_init: bool | None = None,
|
| 42 |
+
kw_only: bool = ...,
|
| 43 |
+
slots: bool = ...,
|
| 44 |
+
) -> Callable[[type[_T]], type[PydanticDataclass]]: # type: ignore
|
| 45 |
+
...
|
| 46 |
+
|
| 47 |
+
@dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr))
|
| 48 |
+
@overload
|
| 49 |
+
def dataclass(
|
| 50 |
+
_cls: type[_T], # type: ignore
|
| 51 |
+
*,
|
| 52 |
+
init: Literal[False] = False,
|
| 53 |
+
repr: bool = True,
|
| 54 |
+
eq: bool = True,
|
| 55 |
+
order: bool = False,
|
| 56 |
+
unsafe_hash: bool = False,
|
| 57 |
+
frozen: bool | None = None,
|
| 58 |
+
config: ConfigDict | type[object] | None = None,
|
| 59 |
+
validate_on_init: bool | None = None,
|
| 60 |
+
kw_only: bool = ...,
|
| 61 |
+
slots: bool = ...,
|
| 62 |
+
) -> type[PydanticDataclass]: ...
|
| 63 |
+
|
| 64 |
+
else:
|
| 65 |
+
|
| 66 |
+
@dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr))
|
| 67 |
+
@overload
|
| 68 |
+
def dataclass(
|
| 69 |
+
*,
|
| 70 |
+
init: Literal[False] = False,
|
| 71 |
+
repr: bool = True,
|
| 72 |
+
eq: bool = True,
|
| 73 |
+
order: bool = False,
|
| 74 |
+
unsafe_hash: bool = False,
|
| 75 |
+
frozen: bool | None = None,
|
| 76 |
+
config: ConfigDict | type[object] | None = None,
|
| 77 |
+
validate_on_init: bool | None = None,
|
| 78 |
+
) -> Callable[[type[_T]], type[PydanticDataclass]]: # type: ignore
|
| 79 |
+
...
|
| 80 |
+
|
| 81 |
+
@dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr))
|
| 82 |
+
@overload
|
| 83 |
+
def dataclass(
|
| 84 |
+
_cls: type[_T], # type: ignore
|
| 85 |
+
*,
|
| 86 |
+
init: Literal[False] = False,
|
| 87 |
+
repr: bool = True,
|
| 88 |
+
eq: bool = True,
|
| 89 |
+
order: bool = False,
|
| 90 |
+
unsafe_hash: bool = False,
|
| 91 |
+
frozen: bool | None = None,
|
| 92 |
+
config: ConfigDict | type[object] | None = None,
|
| 93 |
+
validate_on_init: bool | None = None,
|
| 94 |
+
) -> type[PydanticDataclass]: ...
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
@dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr))
|
| 98 |
+
def dataclass(
|
| 99 |
+
_cls: type[_T] | None = None,
|
| 100 |
+
*,
|
| 101 |
+
init: Literal[False] = False,
|
| 102 |
+
repr: bool = True,
|
| 103 |
+
eq: bool = True,
|
| 104 |
+
order: bool = False,
|
| 105 |
+
unsafe_hash: bool = False,
|
| 106 |
+
frozen: bool | None = None,
|
| 107 |
+
config: ConfigDict | type[object] | None = None,
|
| 108 |
+
validate_on_init: bool | None = None,
|
| 109 |
+
kw_only: bool = False,
|
| 110 |
+
slots: bool = False,
|
| 111 |
+
) -> Callable[[type[_T]], type[PydanticDataclass]] | type[PydanticDataclass]:
|
| 112 |
+
"""Usage docs: https://docs.pydantic.dev/2.10/concepts/dataclasses/
|
| 113 |
+
|
| 114 |
+
A decorator used to create a Pydantic-enhanced dataclass, similar to the standard Python `dataclass`,
|
| 115 |
+
but with added validation.
|
| 116 |
+
|
| 117 |
+
This function should be used similarly to `dataclasses.dataclass`.
|
| 118 |
+
|
| 119 |
+
Args:
|
| 120 |
+
_cls: The target `dataclass`.
|
| 121 |
+
init: Included for signature compatibility with `dataclasses.dataclass`, and is passed through to
|
| 122 |
+
`dataclasses.dataclass` when appropriate. If specified, must be set to `False`, as pydantic inserts its
|
| 123 |
+
own `__init__` function.
|
| 124 |
+
repr: A boolean indicating whether to include the field in the `__repr__` output.
|
| 125 |
+
eq: Determines if a `__eq__` method should be generated for the class.
|
| 126 |
+
order: Determines if comparison magic methods should be generated, such as `__lt__`, but not `__eq__`.
|
| 127 |
+
unsafe_hash: Determines if a `__hash__` method should be included in the class, as in `dataclasses.dataclass`.
|
| 128 |
+
frozen: Determines if the generated class should be a 'frozen' `dataclass`, which does not allow its
|
| 129 |
+
attributes to be modified after it has been initialized. If not set, the value from the provided `config` argument will be used (and will default to `False` otherwise).
|
| 130 |
+
config: The Pydantic config to use for the `dataclass`.
|
| 131 |
+
validate_on_init: A deprecated parameter included for backwards compatibility; in V2, all Pydantic dataclasses
|
| 132 |
+
are validated on init.
|
| 133 |
+
kw_only: Determines if `__init__` method parameters must be specified by keyword only. Defaults to `False`.
|
| 134 |
+
slots: Determines if the generated class should be a 'slots' `dataclass`, which does not allow the addition of
|
| 135 |
+
new attributes after instantiation.
|
| 136 |
+
|
| 137 |
+
Returns:
|
| 138 |
+
A decorator that accepts a class as its argument and returns a Pydantic `dataclass`.
|
| 139 |
+
|
| 140 |
+
Raises:
|
| 141 |
+
AssertionError: Raised if `init` is not `False` or `validate_on_init` is `False`.
|
| 142 |
+
"""
|
| 143 |
+
assert init is False, 'pydantic.dataclasses.dataclass only supports init=False'
|
| 144 |
+
assert validate_on_init is not False, 'validate_on_init=False is no longer supported'
|
| 145 |
+
|
| 146 |
+
if sys.version_info >= (3, 10):
|
| 147 |
+
kwargs = {'kw_only': kw_only, 'slots': slots}
|
| 148 |
+
else:
|
| 149 |
+
kwargs = {}
|
| 150 |
+
|
| 151 |
+
def make_pydantic_fields_compatible(cls: type[Any]) -> None:
|
| 152 |
+
"""Make sure that stdlib `dataclasses` understands `Field` kwargs like `kw_only`
|
| 153 |
+
To do that, we simply change
|
| 154 |
+
`x: int = pydantic.Field(..., kw_only=True)`
|
| 155 |
+
into
|
| 156 |
+
`x: int = dataclasses.field(default=pydantic.Field(..., kw_only=True), kw_only=True)`
|
| 157 |
+
"""
|
| 158 |
+
for annotation_cls in cls.__mro__:
|
| 159 |
+
# In Python < 3.9, `__annotations__` might not be present if there are no fields.
|
| 160 |
+
# we therefore need to use `getattr` to avoid an `AttributeError`.
|
| 161 |
+
annotations = getattr(annotation_cls, '__annotations__', [])
|
| 162 |
+
for field_name in annotations:
|
| 163 |
+
field_value = getattr(cls, field_name, None)
|
| 164 |
+
# Process only if this is an instance of `FieldInfo`.
|
| 165 |
+
if not isinstance(field_value, FieldInfo):
|
| 166 |
+
continue
|
| 167 |
+
|
| 168 |
+
# Initialize arguments for the standard `dataclasses.field`.
|
| 169 |
+
field_args: dict = {'default': field_value}
|
| 170 |
+
|
| 171 |
+
# Handle `kw_only` for Python 3.10+
|
| 172 |
+
if sys.version_info >= (3, 10) and field_value.kw_only:
|
| 173 |
+
field_args['kw_only'] = True
|
| 174 |
+
|
| 175 |
+
# Set `repr` attribute if it's explicitly specified to be not `True`.
|
| 176 |
+
if field_value.repr is not True:
|
| 177 |
+
field_args['repr'] = field_value.repr
|
| 178 |
+
|
| 179 |
+
setattr(cls, field_name, dataclasses.field(**field_args))
|
| 180 |
+
# In Python 3.8, dataclasses checks cls.__dict__['__annotations__'] for annotations,
|
| 181 |
+
# so we must make sure it's initialized before we add to it.
|
| 182 |
+
if cls.__dict__.get('__annotations__') is None:
|
| 183 |
+
cls.__annotations__ = {}
|
| 184 |
+
cls.__annotations__[field_name] = annotations[field_name]
|
| 185 |
+
|
| 186 |
+
def create_dataclass(cls: type[Any]) -> type[PydanticDataclass]:
|
| 187 |
+
"""Create a Pydantic dataclass from a regular dataclass.
|
| 188 |
+
|
| 189 |
+
Args:
|
| 190 |
+
cls: The class to create the Pydantic dataclass from.
|
| 191 |
+
|
| 192 |
+
Returns:
|
| 193 |
+
A Pydantic dataclass.
|
| 194 |
+
"""
|
| 195 |
+
from ._internal._utils import is_model_class
|
| 196 |
+
|
| 197 |
+
if is_model_class(cls):
|
| 198 |
+
raise PydanticUserError(
|
| 199 |
+
f'Cannot create a Pydantic dataclass from {cls.__name__} as it is already a Pydantic model',
|
| 200 |
+
code='dataclass-on-model',
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
original_cls = cls
|
| 204 |
+
|
| 205 |
+
# we warn on conflicting config specifications, but only if the class doesn't have a dataclass base
|
| 206 |
+
# because a dataclass base might provide a __pydantic_config__ attribute that we don't want to warn about
|
| 207 |
+
has_dataclass_base = any(dataclasses.is_dataclass(base) for base in cls.__bases__)
|
| 208 |
+
if not has_dataclass_base and config is not None and hasattr(cls, '__pydantic_config__'):
|
| 209 |
+
warn(
|
| 210 |
+
f'`config` is set via both the `dataclass` decorator and `__pydantic_config__` for dataclass {cls.__name__}. '
|
| 211 |
+
f'The `config` specification from `dataclass` decorator will take priority.',
|
| 212 |
+
category=UserWarning,
|
| 213 |
+
stacklevel=2,
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
# if config is not explicitly provided, try to read it from the type
|
| 217 |
+
config_dict = config if config is not None else getattr(cls, '__pydantic_config__', None)
|
| 218 |
+
config_wrapper = _config.ConfigWrapper(config_dict)
|
| 219 |
+
decorators = _decorators.DecoratorInfos.build(cls)
|
| 220 |
+
|
| 221 |
+
# Keep track of the original __doc__ so that we can restore it after applying the dataclasses decorator
|
| 222 |
+
# Otherwise, classes with no __doc__ will have their signature added into the JSON schema description,
|
| 223 |
+
# since dataclasses.dataclass will set this as the __doc__
|
| 224 |
+
original_doc = cls.__doc__
|
| 225 |
+
|
| 226 |
+
if _pydantic_dataclasses.is_builtin_dataclass(cls):
|
| 227 |
+
# Don't preserve the docstring for vanilla dataclasses, as it may include the signature
|
| 228 |
+
# This matches v1 behavior, and there was an explicit test for it
|
| 229 |
+
original_doc = None
|
| 230 |
+
|
| 231 |
+
# We don't want to add validation to the existing std lib dataclass, so we will subclass it
|
| 232 |
+
# If the class is generic, we need to make sure the subclass also inherits from Generic
|
| 233 |
+
# with all the same parameters.
|
| 234 |
+
bases = (cls,)
|
| 235 |
+
if issubclass(cls, Generic):
|
| 236 |
+
generic_base = Generic[cls.__parameters__] # type: ignore
|
| 237 |
+
bases = bases + (generic_base,)
|
| 238 |
+
cls = types.new_class(cls.__name__, bases)
|
| 239 |
+
|
| 240 |
+
make_pydantic_fields_compatible(cls)
|
| 241 |
+
|
| 242 |
+
# Respect frozen setting from dataclass constructor and fallback to config setting if not provided
|
| 243 |
+
if frozen is not None:
|
| 244 |
+
frozen_ = frozen
|
| 245 |
+
if config_wrapper.frozen:
|
| 246 |
+
# It's not recommended to define both, as the setting from the dataclass decorator will take priority.
|
| 247 |
+
warn(
|
| 248 |
+
f'`frozen` is set via both the `dataclass` decorator and `config` for dataclass {cls.__name__!r}.'
|
| 249 |
+
'This is not recommended. The `frozen` specification on `dataclass` will take priority.',
|
| 250 |
+
category=UserWarning,
|
| 251 |
+
stacklevel=2,
|
| 252 |
+
)
|
| 253 |
+
else:
|
| 254 |
+
frozen_ = config_wrapper.frozen or False
|
| 255 |
+
|
| 256 |
+
cls = dataclasses.dataclass( # type: ignore[call-overload]
|
| 257 |
+
cls,
|
| 258 |
+
# the value of init here doesn't affect anything except that it makes it easier to generate a signature
|
| 259 |
+
init=True,
|
| 260 |
+
repr=repr,
|
| 261 |
+
eq=eq,
|
| 262 |
+
order=order,
|
| 263 |
+
unsafe_hash=unsafe_hash,
|
| 264 |
+
frozen=frozen_,
|
| 265 |
+
**kwargs,
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
cls.__pydantic_decorators__ = decorators # type: ignore
|
| 269 |
+
cls.__doc__ = original_doc
|
| 270 |
+
cls.__module__ = original_cls.__module__
|
| 271 |
+
cls.__qualname__ = original_cls.__qualname__
|
| 272 |
+
cls.__pydantic_complete__ = False # `complete_dataclass` will set it to `True` if successful.
|
| 273 |
+
# TODO `parent_namespace` is currently None, but we could do the same thing as Pydantic models:
|
| 274 |
+
# fetch the parent ns using `parent_frame_namespace` (if the dataclass was defined in a function),
|
| 275 |
+
# and possibly cache it (see the `__pydantic_parent_namespace__` logic for models).
|
| 276 |
+
_pydantic_dataclasses.complete_dataclass(cls, config_wrapper, raise_errors=False)
|
| 277 |
+
return cls
|
| 278 |
+
|
| 279 |
+
return create_dataclass if _cls is None else create_dataclass(_cls)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
__getattr__ = getattr_migration(__name__)
|
| 283 |
+
|
| 284 |
+
if (3, 8) <= sys.version_info < (3, 11):
|
| 285 |
+
# Monkeypatch dataclasses.InitVar so that typing doesn't error if it occurs as a type when evaluating type hints
|
| 286 |
+
# Starting in 3.11, typing.get_type_hints will not raise an error if the retrieved type hints are not callable.
|
| 287 |
+
|
| 288 |
+
def _call_initvar(*args: Any, **kwargs: Any) -> NoReturn:
|
| 289 |
+
"""This function does nothing but raise an error that is as similar as possible to what you'd get
|
| 290 |
+
if you were to try calling `InitVar[int]()` without this monkeypatch. The whole purpose is just
|
| 291 |
+
to ensure typing._type_check does not error if the type hint evaluates to `InitVar[<parameter>]`.
|
| 292 |
+
"""
|
| 293 |
+
raise TypeError("'InitVar' object is not callable")
|
| 294 |
+
|
| 295 |
+
dataclasses.InitVar.__call__ = _call_initvar
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def rebuild_dataclass(
|
| 299 |
+
cls: type[PydanticDataclass],
|
| 300 |
+
*,
|
| 301 |
+
force: bool = False,
|
| 302 |
+
raise_errors: bool = True,
|
| 303 |
+
_parent_namespace_depth: int = 2,
|
| 304 |
+
_types_namespace: MappingNamespace | None = None,
|
| 305 |
+
) -> bool | None:
|
| 306 |
+
"""Try to rebuild the pydantic-core schema for the dataclass.
|
| 307 |
+
|
| 308 |
+
This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
|
| 309 |
+
the initial attempt to build the schema, and automatic rebuilding fails.
|
| 310 |
+
|
| 311 |
+
This is analogous to `BaseModel.model_rebuild`.
|
| 312 |
+
|
| 313 |
+
Args:
|
| 314 |
+
cls: The class to rebuild the pydantic-core schema for.
|
| 315 |
+
force: Whether to force the rebuilding of the schema, defaults to `False`.
|
| 316 |
+
raise_errors: Whether to raise errors, defaults to `True`.
|
| 317 |
+
_parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
|
| 318 |
+
_types_namespace: The types namespace, defaults to `None`.
|
| 319 |
+
|
| 320 |
+
Returns:
|
| 321 |
+
Returns `None` if the schema is already "complete" and rebuilding was not required.
|
| 322 |
+
If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| 323 |
+
"""
|
| 324 |
+
if not force and cls.__pydantic_complete__:
|
| 325 |
+
return None
|
| 326 |
+
|
| 327 |
+
if '__pydantic_core_schema__' in cls.__dict__:
|
| 328 |
+
delattr(cls, '__pydantic_core_schema__') # delete cached value to ensure full rebuild happens
|
| 329 |
+
|
| 330 |
+
if _types_namespace is not None:
|
| 331 |
+
rebuild_ns = _types_namespace
|
| 332 |
+
elif _parent_namespace_depth > 0:
|
| 333 |
+
rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
|
| 334 |
+
else:
|
| 335 |
+
rebuild_ns = {}
|
| 336 |
+
|
| 337 |
+
ns_resolver = _namespace_utils.NsResolver(
|
| 338 |
+
parent_namespace=rebuild_ns,
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
return _pydantic_dataclasses.complete_dataclass(
|
| 342 |
+
cls,
|
| 343 |
+
_config.ConfigWrapper(cls.__pydantic_config__, check=False),
|
| 344 |
+
raise_errors=raise_errors,
|
| 345 |
+
ns_resolver=ns_resolver,
|
| 346 |
+
# We could provide a different config instead (with `'defer_build'` set to `True`)
|
| 347 |
+
# of this explicit `_force_build` argument, but because config can come from the
|
| 348 |
+
# decorator parameter or the `__pydantic_config__` attribute, `complete_dataclass`
|
| 349 |
+
# will overwrite `__pydantic_config__` with the provided config above:
|
| 350 |
+
_force_build=True,
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def is_pydantic_dataclass(class_: type[Any], /) -> TypeGuard[type[PydanticDataclass]]:
|
| 355 |
+
"""Whether a class is a pydantic dataclass.
|
| 356 |
+
|
| 357 |
+
Args:
|
| 358 |
+
class_: The class.
|
| 359 |
+
|
| 360 |
+
Returns:
|
| 361 |
+
`True` if the class is a pydantic dataclass, `False` otherwise.
|
| 362 |
+
"""
|
| 363 |
+
try:
|
| 364 |
+
return '__pydantic_validator__' in class_.__dict__ and dataclasses.is_dataclass(class_)
|
| 365 |
+
except AttributeError:
|
| 366 |
+
return False
|
vllm/lib/python3.10/site-packages/pydantic/datetime_parse.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The `datetime_parse` module is a backport module from V1."""
|
| 2 |
+
|
| 3 |
+
from ._migration import getattr_migration
|
| 4 |
+
|
| 5 |
+
__getattr__ = getattr_migration(__name__)
|
vllm/lib/python3.10/site-packages/pydantic/decorator.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The `decorator` module is a backport module from V1."""
|
| 2 |
+
|
| 3 |
+
from ._migration import getattr_migration
|
| 4 |
+
|
| 5 |
+
__getattr__ = getattr_migration(__name__)
|
vllm/lib/python3.10/site-packages/pydantic/deprecated/__init__.py
ADDED
|
File without changes
|
vllm/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (169 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/class_validators.cpython-310.pyc
ADDED
|
Binary file (9.84 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/config.cpython-310.pyc
ADDED
|
Binary file (3.1 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/copy_internals.cpython-310.pyc
ADDED
|
Binary file (5.16 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/decorator.cpython-310.pyc
ADDED
|
Binary file (8.75 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/json.cpython-310.pyc
ADDED
|
Binary file (4.27 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/parse.cpython-310.pyc
ADDED
|
Binary file (2.23 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/tools.cpython-310.pyc
ADDED
|
Binary file (2.69 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/pydantic/deprecated/class_validators.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Old `@validator` and `@root_validator` function validators from V1."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations as _annotations
|
| 4 |
+
|
| 5 |
+
from functools import partial, partialmethod
|
| 6 |
+
from types import FunctionType
|
| 7 |
+
from typing import TYPE_CHECKING, Any, Callable, TypeVar, Union, overload
|
| 8 |
+
from warnings import warn
|
| 9 |
+
|
| 10 |
+
from typing_extensions import Literal, Protocol, TypeAlias, deprecated
|
| 11 |
+
|
| 12 |
+
from .._internal import _decorators, _decorators_v1
|
| 13 |
+
from ..errors import PydanticUserError
|
| 14 |
+
from ..warnings import PydanticDeprecatedSince20
|
| 15 |
+
|
| 16 |
+
_ALLOW_REUSE_WARNING_MESSAGE = '`allow_reuse` is deprecated and will be ignored; it should no longer be necessary'
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
|
| 21 |
+
class _OnlyValueValidatorClsMethod(Protocol):
|
| 22 |
+
def __call__(self, __cls: Any, __value: Any) -> Any: ...
|
| 23 |
+
|
| 24 |
+
class _V1ValidatorWithValuesClsMethod(Protocol):
|
| 25 |
+
def __call__(self, __cls: Any, __value: Any, values: dict[str, Any]) -> Any: ...
|
| 26 |
+
|
| 27 |
+
class _V1ValidatorWithValuesKwOnlyClsMethod(Protocol):
|
| 28 |
+
def __call__(self, __cls: Any, __value: Any, *, values: dict[str, Any]) -> Any: ...
|
| 29 |
+
|
| 30 |
+
class _V1ValidatorWithKwargsClsMethod(Protocol):
|
| 31 |
+
def __call__(self, __cls: Any, **kwargs: Any) -> Any: ...
|
| 32 |
+
|
| 33 |
+
class _V1ValidatorWithValuesAndKwargsClsMethod(Protocol):
|
| 34 |
+
def __call__(self, __cls: Any, values: dict[str, Any], **kwargs: Any) -> Any: ...
|
| 35 |
+
|
| 36 |
+
class _V1RootValidatorClsMethod(Protocol):
|
| 37 |
+
def __call__(
|
| 38 |
+
self, __cls: Any, __values: _decorators_v1.RootValidatorValues
|
| 39 |
+
) -> _decorators_v1.RootValidatorValues: ...
|
| 40 |
+
|
| 41 |
+
V1Validator = Union[
|
| 42 |
+
_OnlyValueValidatorClsMethod,
|
| 43 |
+
_V1ValidatorWithValuesClsMethod,
|
| 44 |
+
_V1ValidatorWithValuesKwOnlyClsMethod,
|
| 45 |
+
_V1ValidatorWithKwargsClsMethod,
|
| 46 |
+
_V1ValidatorWithValuesAndKwargsClsMethod,
|
| 47 |
+
_decorators_v1.V1ValidatorWithValues,
|
| 48 |
+
_decorators_v1.V1ValidatorWithValuesKwOnly,
|
| 49 |
+
_decorators_v1.V1ValidatorWithKwargs,
|
| 50 |
+
_decorators_v1.V1ValidatorWithValuesAndKwargs,
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
V1RootValidator = Union[
|
| 54 |
+
_V1RootValidatorClsMethod,
|
| 55 |
+
_decorators_v1.V1RootValidatorFunction,
|
| 56 |
+
]
|
| 57 |
+
|
| 58 |
+
_PartialClsOrStaticMethod: TypeAlias = Union[classmethod[Any, Any, Any], staticmethod[Any, Any], partialmethod[Any]]
|
| 59 |
+
|
| 60 |
+
# Allow both a V1 (assumed pre=False) or V2 (assumed mode='after') validator
|
| 61 |
+
# We lie to type checkers and say we return the same thing we get
|
| 62 |
+
# but in reality we return a proxy object that _mostly_ behaves like the wrapped thing
|
| 63 |
+
_V1ValidatorType = TypeVar('_V1ValidatorType', V1Validator, _PartialClsOrStaticMethod)
|
| 64 |
+
_V1RootValidatorFunctionType = TypeVar(
|
| 65 |
+
'_V1RootValidatorFunctionType',
|
| 66 |
+
_decorators_v1.V1RootValidatorFunction,
|
| 67 |
+
_V1RootValidatorClsMethod,
|
| 68 |
+
_PartialClsOrStaticMethod,
|
| 69 |
+
)
|
| 70 |
+
else:
|
| 71 |
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
| 72 |
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
| 73 |
+
DeprecationWarning = PydanticDeprecatedSince20
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@deprecated(
|
| 77 |
+
'Pydantic V1 style `@validator` validators are deprecated.'
|
| 78 |
+
' You should migrate to Pydantic V2 style `@field_validator` validators,'
|
| 79 |
+
' see the migration guide for more details',
|
| 80 |
+
category=None,
|
| 81 |
+
)
|
| 82 |
+
def validator(
|
| 83 |
+
__field: str,
|
| 84 |
+
*fields: str,
|
| 85 |
+
pre: bool = False,
|
| 86 |
+
each_item: bool = False,
|
| 87 |
+
always: bool = False,
|
| 88 |
+
check_fields: bool | None = None,
|
| 89 |
+
allow_reuse: bool = False,
|
| 90 |
+
) -> Callable[[_V1ValidatorType], _V1ValidatorType]:
|
| 91 |
+
"""Decorate methods on the class indicating that they should be used to validate fields.
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
__field (str): The first field the validator should be called on; this is separate
|
| 95 |
+
from `fields` to ensure an error is raised if you don't pass at least one.
|
| 96 |
+
*fields (str): Additional field(s) the validator should be called on.
|
| 97 |
+
pre (bool, optional): Whether this validator should be called before the standard
|
| 98 |
+
validators (else after). Defaults to False.
|
| 99 |
+
each_item (bool, optional): For complex objects (sets, lists etc.) whether to validate
|
| 100 |
+
individual elements rather than the whole object. Defaults to False.
|
| 101 |
+
always (bool, optional): Whether this method and other validators should be called even if
|
| 102 |
+
the value is missing. Defaults to False.
|
| 103 |
+
check_fields (bool | None, optional): Whether to check that the fields actually exist on the model.
|
| 104 |
+
Defaults to None.
|
| 105 |
+
allow_reuse (bool, optional): Whether to track and raise an error if another validator refers to
|
| 106 |
+
the decorated function. Defaults to False.
|
| 107 |
+
|
| 108 |
+
Returns:
|
| 109 |
+
Callable: A decorator that can be used to decorate a
|
| 110 |
+
function to be used as a validator.
|
| 111 |
+
"""
|
| 112 |
+
warn(
|
| 113 |
+
'Pydantic V1 style `@validator` validators are deprecated.'
|
| 114 |
+
' You should migrate to Pydantic V2 style `@field_validator` validators,'
|
| 115 |
+
' see the migration guide for more details',
|
| 116 |
+
DeprecationWarning,
|
| 117 |
+
stacklevel=2,
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
if allow_reuse is True: # pragma: no cover
|
| 121 |
+
warn(_ALLOW_REUSE_WARNING_MESSAGE, DeprecationWarning)
|
| 122 |
+
fields = __field, *fields
|
| 123 |
+
if isinstance(fields[0], FunctionType):
|
| 124 |
+
raise PydanticUserError(
|
| 125 |
+
'`@validator` should be used with fields and keyword arguments, not bare. '
|
| 126 |
+
"E.g. usage should be `@validator('<field_name>', ...)`",
|
| 127 |
+
code='validator-no-fields',
|
| 128 |
+
)
|
| 129 |
+
elif not all(isinstance(field, str) for field in fields):
|
| 130 |
+
raise PydanticUserError(
|
| 131 |
+
'`@validator` fields should be passed as separate string args. '
|
| 132 |
+
"E.g. usage should be `@validator('<field_name_1>', '<field_name_2>', ...)`",
|
| 133 |
+
code='validator-invalid-fields',
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
mode: Literal['before', 'after'] = 'before' if pre is True else 'after'
|
| 137 |
+
|
| 138 |
+
def dec(f: Any) -> _decorators.PydanticDescriptorProxy[Any]:
|
| 139 |
+
if _decorators.is_instance_method_from_sig(f):
|
| 140 |
+
raise PydanticUserError(
|
| 141 |
+
'`@validator` cannot be applied to instance methods', code='validator-instance-method'
|
| 142 |
+
)
|
| 143 |
+
# auto apply the @classmethod decorator
|
| 144 |
+
f = _decorators.ensure_classmethod_based_on_signature(f)
|
| 145 |
+
wrap = _decorators_v1.make_generic_v1_field_validator
|
| 146 |
+
validator_wrapper_info = _decorators.ValidatorDecoratorInfo(
|
| 147 |
+
fields=fields,
|
| 148 |
+
mode=mode,
|
| 149 |
+
each_item=each_item,
|
| 150 |
+
always=always,
|
| 151 |
+
check_fields=check_fields,
|
| 152 |
+
)
|
| 153 |
+
return _decorators.PydanticDescriptorProxy(f, validator_wrapper_info, shim=wrap)
|
| 154 |
+
|
| 155 |
+
return dec # type: ignore[return-value]
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
@overload
|
| 159 |
+
def root_validator(
|
| 160 |
+
*,
|
| 161 |
+
# if you don't specify `pre` the default is `pre=False`
|
| 162 |
+
# which means you need to specify `skip_on_failure=True`
|
| 163 |
+
skip_on_failure: Literal[True],
|
| 164 |
+
allow_reuse: bool = ...,
|
| 165 |
+
) -> Callable[
|
| 166 |
+
[_V1RootValidatorFunctionType],
|
| 167 |
+
_V1RootValidatorFunctionType,
|
| 168 |
+
]: ...
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
@overload
|
| 172 |
+
def root_validator(
|
| 173 |
+
*,
|
| 174 |
+
# if you specify `pre=True` then you don't need to specify
|
| 175 |
+
# `skip_on_failure`, in fact it is not allowed as an argument!
|
| 176 |
+
pre: Literal[True],
|
| 177 |
+
allow_reuse: bool = ...,
|
| 178 |
+
) -> Callable[
|
| 179 |
+
[_V1RootValidatorFunctionType],
|
| 180 |
+
_V1RootValidatorFunctionType,
|
| 181 |
+
]: ...
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
@overload
|
| 185 |
+
def root_validator(
|
| 186 |
+
*,
|
| 187 |
+
# if you explicitly specify `pre=False` then you
|
| 188 |
+
# MUST specify `skip_on_failure=True`
|
| 189 |
+
pre: Literal[False],
|
| 190 |
+
skip_on_failure: Literal[True],
|
| 191 |
+
allow_reuse: bool = ...,
|
| 192 |
+
) -> Callable[
|
| 193 |
+
[_V1RootValidatorFunctionType],
|
| 194 |
+
_V1RootValidatorFunctionType,
|
| 195 |
+
]: ...
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
@deprecated(
|
| 199 |
+
'Pydantic V1 style `@root_validator` validators are deprecated.'
|
| 200 |
+
' You should migrate to Pydantic V2 style `@model_validator` validators,'
|
| 201 |
+
' see the migration guide for more details',
|
| 202 |
+
category=None,
|
| 203 |
+
)
|
| 204 |
+
def root_validator(
|
| 205 |
+
*__args,
|
| 206 |
+
pre: bool = False,
|
| 207 |
+
skip_on_failure: bool = False,
|
| 208 |
+
allow_reuse: bool = False,
|
| 209 |
+
) -> Any:
|
| 210 |
+
"""Decorate methods on a model indicating that they should be used to validate (and perhaps
|
| 211 |
+
modify) data either before or after standard model parsing/validation is performed.
|
| 212 |
+
|
| 213 |
+
Args:
|
| 214 |
+
pre (bool, optional): Whether this validator should be called before the standard
|
| 215 |
+
validators (else after). Defaults to False.
|
| 216 |
+
skip_on_failure (bool, optional): Whether to stop validation and return as soon as a
|
| 217 |
+
failure is encountered. Defaults to False.
|
| 218 |
+
allow_reuse (bool, optional): Whether to track and raise an error if another validator
|
| 219 |
+
refers to the decorated function. Defaults to False.
|
| 220 |
+
|
| 221 |
+
Returns:
|
| 222 |
+
Any: A decorator that can be used to decorate a function to be used as a root_validator.
|
| 223 |
+
"""
|
| 224 |
+
warn(
|
| 225 |
+
'Pydantic V1 style `@root_validator` validators are deprecated.'
|
| 226 |
+
' You should migrate to Pydantic V2 style `@model_validator` validators,'
|
| 227 |
+
' see the migration guide for more details',
|
| 228 |
+
DeprecationWarning,
|
| 229 |
+
stacklevel=2,
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
if __args:
|
| 233 |
+
# Ensure a nice error is raised if someone attempts to use the bare decorator
|
| 234 |
+
return root_validator()(*__args) # type: ignore
|
| 235 |
+
|
| 236 |
+
if allow_reuse is True: # pragma: no cover
|
| 237 |
+
warn(_ALLOW_REUSE_WARNING_MESSAGE, DeprecationWarning)
|
| 238 |
+
mode: Literal['before', 'after'] = 'before' if pre is True else 'after'
|
| 239 |
+
if pre is False and skip_on_failure is not True:
|
| 240 |
+
raise PydanticUserError(
|
| 241 |
+
'If you use `@root_validator` with pre=False (the default) you MUST specify `skip_on_failure=True`.'
|
| 242 |
+
' Note that `@root_validator` is deprecated and should be replaced with `@model_validator`.',
|
| 243 |
+
code='root-validator-pre-skip',
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
wrap = partial(_decorators_v1.make_v1_generic_root_validator, pre=pre)
|
| 247 |
+
|
| 248 |
+
def dec(f: Callable[..., Any] | classmethod[Any, Any, Any] | staticmethod[Any, Any]) -> Any:
|
| 249 |
+
if _decorators.is_instance_method_from_sig(f):
|
| 250 |
+
raise TypeError('`@root_validator` cannot be applied to instance methods')
|
| 251 |
+
# auto apply the @classmethod decorator
|
| 252 |
+
res = _decorators.ensure_classmethod_based_on_signature(f)
|
| 253 |
+
dec_info = _decorators.RootValidatorDecoratorInfo(mode=mode)
|
| 254 |
+
return _decorators.PydanticDescriptorProxy(res, dec_info, shim=wrap)
|
| 255 |
+
|
| 256 |
+
return dec
|
vllm/lib/python3.10/site-packages/pydantic/deprecated/config.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations as _annotations
|
| 2 |
+
|
| 3 |
+
import warnings
|
| 4 |
+
from typing import TYPE_CHECKING, Any
|
| 5 |
+
|
| 6 |
+
from typing_extensions import Literal, deprecated
|
| 7 |
+
|
| 8 |
+
from .._internal import _config
|
| 9 |
+
from ..warnings import PydanticDeprecatedSince20
|
| 10 |
+
|
| 11 |
+
if not TYPE_CHECKING:
|
| 12 |
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
| 13 |
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
| 14 |
+
DeprecationWarning = PydanticDeprecatedSince20
|
| 15 |
+
|
| 16 |
+
__all__ = 'BaseConfig', 'Extra'
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class _ConfigMetaclass(type):
|
| 20 |
+
def __getattr__(self, item: str) -> Any:
|
| 21 |
+
try:
|
| 22 |
+
obj = _config.config_defaults[item]
|
| 23 |
+
warnings.warn(_config.DEPRECATION_MESSAGE, DeprecationWarning)
|
| 24 |
+
return obj
|
| 25 |
+
except KeyError as exc:
|
| 26 |
+
raise AttributeError(f"type object '{self.__name__}' has no attribute {exc}") from exc
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@deprecated('BaseConfig is deprecated. Use the `pydantic.ConfigDict` instead.', category=PydanticDeprecatedSince20)
|
| 30 |
+
class BaseConfig(metaclass=_ConfigMetaclass):
|
| 31 |
+
"""This class is only retained for backwards compatibility.
|
| 32 |
+
|
| 33 |
+
!!! Warning "Deprecated"
|
| 34 |
+
BaseConfig is deprecated. Use the [`pydantic.ConfigDict`][pydantic.ConfigDict] instead.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __getattr__(self, item: str) -> Any:
|
| 38 |
+
try:
|
| 39 |
+
obj = super().__getattribute__(item)
|
| 40 |
+
warnings.warn(_config.DEPRECATION_MESSAGE, DeprecationWarning)
|
| 41 |
+
return obj
|
| 42 |
+
except AttributeError as exc:
|
| 43 |
+
try:
|
| 44 |
+
return getattr(type(self), item)
|
| 45 |
+
except AttributeError:
|
| 46 |
+
# re-raising changes the displayed text to reflect that `self` is not a type
|
| 47 |
+
raise AttributeError(str(exc)) from exc
|
| 48 |
+
|
| 49 |
+
def __init_subclass__(cls, **kwargs: Any) -> None:
|
| 50 |
+
warnings.warn(_config.DEPRECATION_MESSAGE, DeprecationWarning)
|
| 51 |
+
return super().__init_subclass__(**kwargs)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class _ExtraMeta(type):
|
| 55 |
+
def __getattribute__(self, __name: str) -> Any:
|
| 56 |
+
# The @deprecated decorator accesses other attributes, so we only emit a warning for the expected ones
|
| 57 |
+
if __name in {'allow', 'ignore', 'forbid'}:
|
| 58 |
+
warnings.warn(
|
| 59 |
+
"`pydantic.config.Extra` is deprecated, use literal values instead (e.g. `extra='allow'`)",
|
| 60 |
+
DeprecationWarning,
|
| 61 |
+
stacklevel=2,
|
| 62 |
+
)
|
| 63 |
+
return super().__getattribute__(__name)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@deprecated(
|
| 67 |
+
"Extra is deprecated. Use literal values instead (e.g. `extra='allow'`)", category=PydanticDeprecatedSince20
|
| 68 |
+
)
|
| 69 |
+
class Extra(metaclass=_ExtraMeta):
|
| 70 |
+
allow: Literal['allow'] = 'allow'
|
| 71 |
+
ignore: Literal['ignore'] = 'ignore'
|
| 72 |
+
forbid: Literal['forbid'] = 'forbid'
|
vllm/lib/python3.10/site-packages/pydantic/deprecated/copy_internals.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations as _annotations
|
| 2 |
+
|
| 3 |
+
import typing
|
| 4 |
+
from copy import deepcopy
|
| 5 |
+
from enum import Enum
|
| 6 |
+
from typing import Any, Tuple
|
| 7 |
+
|
| 8 |
+
import typing_extensions
|
| 9 |
+
|
| 10 |
+
from .._internal import (
|
| 11 |
+
_model_construction,
|
| 12 |
+
_typing_extra,
|
| 13 |
+
_utils,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
if typing.TYPE_CHECKING:
|
| 17 |
+
from .. import BaseModel
|
| 18 |
+
from .._internal._utils import AbstractSetIntStr, MappingIntStrAny
|
| 19 |
+
|
| 20 |
+
AnyClassMethod = classmethod[Any, Any, Any]
|
| 21 |
+
TupleGenerator = typing.Generator[Tuple[str, Any], None, None]
|
| 22 |
+
Model = typing.TypeVar('Model', bound='BaseModel')
|
| 23 |
+
# should be `set[int] | set[str] | dict[int, IncEx] | dict[str, IncEx] | None`, but mypy can't cope
|
| 24 |
+
IncEx: typing_extensions.TypeAlias = 'set[int] | set[str] | dict[int, Any] | dict[str, Any] | None'
|
| 25 |
+
|
| 26 |
+
_object_setattr = _model_construction.object_setattr
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _iter(
|
| 30 |
+
self: BaseModel,
|
| 31 |
+
to_dict: bool = False,
|
| 32 |
+
by_alias: bool = False,
|
| 33 |
+
include: AbstractSetIntStr | MappingIntStrAny | None = None,
|
| 34 |
+
exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
|
| 35 |
+
exclude_unset: bool = False,
|
| 36 |
+
exclude_defaults: bool = False,
|
| 37 |
+
exclude_none: bool = False,
|
| 38 |
+
) -> TupleGenerator:
|
| 39 |
+
# Merge field set excludes with explicit exclude parameter with explicit overriding field set options.
|
| 40 |
+
# The extra "is not None" guards are not logically necessary but optimizes performance for the simple case.
|
| 41 |
+
if exclude is not None:
|
| 42 |
+
exclude = _utils.ValueItems.merge(
|
| 43 |
+
{k: v.exclude for k, v in self.__pydantic_fields__.items() if v.exclude is not None}, exclude
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
if include is not None:
|
| 47 |
+
include = _utils.ValueItems.merge({k: True for k in self.__pydantic_fields__}, include, intersect=True)
|
| 48 |
+
|
| 49 |
+
allowed_keys = _calculate_keys(self, include=include, exclude=exclude, exclude_unset=exclude_unset) # type: ignore
|
| 50 |
+
if allowed_keys is None and not (to_dict or by_alias or exclude_unset or exclude_defaults or exclude_none):
|
| 51 |
+
# huge boost for plain _iter()
|
| 52 |
+
yield from self.__dict__.items()
|
| 53 |
+
if self.__pydantic_extra__:
|
| 54 |
+
yield from self.__pydantic_extra__.items()
|
| 55 |
+
return
|
| 56 |
+
|
| 57 |
+
value_exclude = _utils.ValueItems(self, exclude) if exclude is not None else None
|
| 58 |
+
value_include = _utils.ValueItems(self, include) if include is not None else None
|
| 59 |
+
|
| 60 |
+
if self.__pydantic_extra__ is None:
|
| 61 |
+
items = self.__dict__.items()
|
| 62 |
+
else:
|
| 63 |
+
items = list(self.__dict__.items()) + list(self.__pydantic_extra__.items())
|
| 64 |
+
|
| 65 |
+
for field_key, v in items:
|
| 66 |
+
if (allowed_keys is not None and field_key not in allowed_keys) or (exclude_none and v is None):
|
| 67 |
+
continue
|
| 68 |
+
|
| 69 |
+
if exclude_defaults:
|
| 70 |
+
try:
|
| 71 |
+
field = self.__pydantic_fields__[field_key]
|
| 72 |
+
except KeyError:
|
| 73 |
+
pass
|
| 74 |
+
else:
|
| 75 |
+
if not field.is_required() and field.default == v:
|
| 76 |
+
continue
|
| 77 |
+
|
| 78 |
+
if by_alias and field_key in self.__pydantic_fields__:
|
| 79 |
+
dict_key = self.__pydantic_fields__[field_key].alias or field_key
|
| 80 |
+
else:
|
| 81 |
+
dict_key = field_key
|
| 82 |
+
|
| 83 |
+
if to_dict or value_include or value_exclude:
|
| 84 |
+
v = _get_value(
|
| 85 |
+
type(self),
|
| 86 |
+
v,
|
| 87 |
+
to_dict=to_dict,
|
| 88 |
+
by_alias=by_alias,
|
| 89 |
+
include=value_include and value_include.for_element(field_key),
|
| 90 |
+
exclude=value_exclude and value_exclude.for_element(field_key),
|
| 91 |
+
exclude_unset=exclude_unset,
|
| 92 |
+
exclude_defaults=exclude_defaults,
|
| 93 |
+
exclude_none=exclude_none,
|
| 94 |
+
)
|
| 95 |
+
yield dict_key, v
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _copy_and_set_values(
|
| 99 |
+
self: Model,
|
| 100 |
+
values: dict[str, Any],
|
| 101 |
+
fields_set: set[str],
|
| 102 |
+
extra: dict[str, Any] | None = None,
|
| 103 |
+
private: dict[str, Any] | None = None,
|
| 104 |
+
*,
|
| 105 |
+
deep: bool, # UP006
|
| 106 |
+
) -> Model:
|
| 107 |
+
if deep:
|
| 108 |
+
# chances of having empty dict here are quite low for using smart_deepcopy
|
| 109 |
+
values = deepcopy(values)
|
| 110 |
+
extra = deepcopy(extra)
|
| 111 |
+
private = deepcopy(private)
|
| 112 |
+
|
| 113 |
+
cls = self.__class__
|
| 114 |
+
m = cls.__new__(cls)
|
| 115 |
+
_object_setattr(m, '__dict__', values)
|
| 116 |
+
_object_setattr(m, '__pydantic_extra__', extra)
|
| 117 |
+
_object_setattr(m, '__pydantic_fields_set__', fields_set)
|
| 118 |
+
_object_setattr(m, '__pydantic_private__', private)
|
| 119 |
+
|
| 120 |
+
return m
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@typing.no_type_check
|
| 124 |
+
def _get_value(
|
| 125 |
+
cls: type[BaseModel],
|
| 126 |
+
v: Any,
|
| 127 |
+
to_dict: bool,
|
| 128 |
+
by_alias: bool,
|
| 129 |
+
include: AbstractSetIntStr | MappingIntStrAny | None,
|
| 130 |
+
exclude: AbstractSetIntStr | MappingIntStrAny | None,
|
| 131 |
+
exclude_unset: bool,
|
| 132 |
+
exclude_defaults: bool,
|
| 133 |
+
exclude_none: bool,
|
| 134 |
+
) -> Any:
|
| 135 |
+
from .. import BaseModel
|
| 136 |
+
|
| 137 |
+
if isinstance(v, BaseModel):
|
| 138 |
+
if to_dict:
|
| 139 |
+
return v.model_dump(
|
| 140 |
+
by_alias=by_alias,
|
| 141 |
+
exclude_unset=exclude_unset,
|
| 142 |
+
exclude_defaults=exclude_defaults,
|
| 143 |
+
include=include, # type: ignore
|
| 144 |
+
exclude=exclude, # type: ignore
|
| 145 |
+
exclude_none=exclude_none,
|
| 146 |
+
)
|
| 147 |
+
else:
|
| 148 |
+
return v.copy(include=include, exclude=exclude)
|
| 149 |
+
|
| 150 |
+
value_exclude = _utils.ValueItems(v, exclude) if exclude else None
|
| 151 |
+
value_include = _utils.ValueItems(v, include) if include else None
|
| 152 |
+
|
| 153 |
+
if isinstance(v, dict):
|
| 154 |
+
return {
|
| 155 |
+
k_: _get_value(
|
| 156 |
+
cls,
|
| 157 |
+
v_,
|
| 158 |
+
to_dict=to_dict,
|
| 159 |
+
by_alias=by_alias,
|
| 160 |
+
exclude_unset=exclude_unset,
|
| 161 |
+
exclude_defaults=exclude_defaults,
|
| 162 |
+
include=value_include and value_include.for_element(k_),
|
| 163 |
+
exclude=value_exclude and value_exclude.for_element(k_),
|
| 164 |
+
exclude_none=exclude_none,
|
| 165 |
+
)
|
| 166 |
+
for k_, v_ in v.items()
|
| 167 |
+
if (not value_exclude or not value_exclude.is_excluded(k_))
|
| 168 |
+
and (not value_include or value_include.is_included(k_))
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
elif _utils.sequence_like(v):
|
| 172 |
+
seq_args = (
|
| 173 |
+
_get_value(
|
| 174 |
+
cls,
|
| 175 |
+
v_,
|
| 176 |
+
to_dict=to_dict,
|
| 177 |
+
by_alias=by_alias,
|
| 178 |
+
exclude_unset=exclude_unset,
|
| 179 |
+
exclude_defaults=exclude_defaults,
|
| 180 |
+
include=value_include and value_include.for_element(i),
|
| 181 |
+
exclude=value_exclude and value_exclude.for_element(i),
|
| 182 |
+
exclude_none=exclude_none,
|
| 183 |
+
)
|
| 184 |
+
for i, v_ in enumerate(v)
|
| 185 |
+
if (not value_exclude or not value_exclude.is_excluded(i))
|
| 186 |
+
and (not value_include or value_include.is_included(i))
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
return v.__class__(*seq_args) if _typing_extra.is_namedtuple(v.__class__) else v.__class__(seq_args)
|
| 190 |
+
|
| 191 |
+
elif isinstance(v, Enum) and getattr(cls.model_config, 'use_enum_values', False):
|
| 192 |
+
return v.value
|
| 193 |
+
|
| 194 |
+
else:
|
| 195 |
+
return v
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def _calculate_keys(
|
| 199 |
+
self: BaseModel,
|
| 200 |
+
include: MappingIntStrAny | None,
|
| 201 |
+
exclude: MappingIntStrAny | None,
|
| 202 |
+
exclude_unset: bool,
|
| 203 |
+
update: typing.Dict[str, Any] | None = None, # noqa UP006
|
| 204 |
+
) -> typing.AbstractSet[str] | None:
|
| 205 |
+
if include is None and exclude is None and exclude_unset is False:
|
| 206 |
+
return None
|
| 207 |
+
|
| 208 |
+
keys: typing.AbstractSet[str]
|
| 209 |
+
if exclude_unset:
|
| 210 |
+
keys = self.__pydantic_fields_set__.copy()
|
| 211 |
+
else:
|
| 212 |
+
keys = set(self.__dict__.keys())
|
| 213 |
+
keys = keys | (self.__pydantic_extra__ or {}).keys()
|
| 214 |
+
|
| 215 |
+
if include is not None:
|
| 216 |
+
keys &= include.keys()
|
| 217 |
+
|
| 218 |
+
if update:
|
| 219 |
+
keys -= update.keys()
|
| 220 |
+
|
| 221 |
+
if exclude:
|
| 222 |
+
keys -= {k for k, v in exclude.items() if _utils.ValueItems.is_true(v)}
|
| 223 |
+
|
| 224 |
+
return keys
|
vllm/lib/python3.10/site-packages/pydantic/deprecated/decorator.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
from functools import wraps
|
| 3 |
+
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional, Tuple, Type, TypeVar, Union, overload
|
| 4 |
+
|
| 5 |
+
from typing_extensions import deprecated
|
| 6 |
+
|
| 7 |
+
from .._internal import _config, _typing_extra
|
| 8 |
+
from ..alias_generators import to_pascal
|
| 9 |
+
from ..errors import PydanticUserError
|
| 10 |
+
from ..functional_validators import field_validator
|
| 11 |
+
from ..main import BaseModel, create_model
|
| 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__ = ('validate_arguments',)
|
| 20 |
+
|
| 21 |
+
if TYPE_CHECKING:
|
| 22 |
+
AnyCallable = Callable[..., Any]
|
| 23 |
+
|
| 24 |
+
AnyCallableT = TypeVar('AnyCallableT', bound=AnyCallable)
|
| 25 |
+
ConfigType = Union[None, Type[Any], Dict[str, Any]]
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@overload
|
| 29 |
+
def validate_arguments(
|
| 30 |
+
func: None = None, *, config: 'ConfigType' = None
|
| 31 |
+
) -> Callable[['AnyCallableT'], 'AnyCallableT']: ...
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@overload
|
| 35 |
+
def validate_arguments(func: 'AnyCallableT') -> 'AnyCallableT': ...
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@deprecated(
|
| 39 |
+
'The `validate_arguments` method is deprecated; use `validate_call` instead.',
|
| 40 |
+
category=None,
|
| 41 |
+
)
|
| 42 |
+
def validate_arguments(func: Optional['AnyCallableT'] = None, *, config: 'ConfigType' = None) -> Any:
|
| 43 |
+
"""Decorator to validate the arguments passed to a function."""
|
| 44 |
+
warnings.warn(
|
| 45 |
+
'The `validate_arguments` method is deprecated; use `validate_call` instead.',
|
| 46 |
+
PydanticDeprecatedSince20,
|
| 47 |
+
stacklevel=2,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
def validate(_func: 'AnyCallable') -> 'AnyCallable':
|
| 51 |
+
vd = ValidatedFunction(_func, config)
|
| 52 |
+
|
| 53 |
+
@wraps(_func)
|
| 54 |
+
def wrapper_function(*args: Any, **kwargs: Any) -> Any:
|
| 55 |
+
return vd.call(*args, **kwargs)
|
| 56 |
+
|
| 57 |
+
wrapper_function.vd = vd # type: ignore
|
| 58 |
+
wrapper_function.validate = vd.init_model_instance # type: ignore
|
| 59 |
+
wrapper_function.raw_function = vd.raw_function # type: ignore
|
| 60 |
+
wrapper_function.model = vd.model # type: ignore
|
| 61 |
+
return wrapper_function
|
| 62 |
+
|
| 63 |
+
if func:
|
| 64 |
+
return validate(func)
|
| 65 |
+
else:
|
| 66 |
+
return validate
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
ALT_V_ARGS = 'v__args'
|
| 70 |
+
ALT_V_KWARGS = 'v__kwargs'
|
| 71 |
+
V_POSITIONAL_ONLY_NAME = 'v__positional_only'
|
| 72 |
+
V_DUPLICATE_KWARGS = 'v__duplicate_kwargs'
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class ValidatedFunction:
|
| 76 |
+
def __init__(self, function: 'AnyCallable', config: 'ConfigType'):
|
| 77 |
+
from inspect import Parameter, signature
|
| 78 |
+
|
| 79 |
+
parameters: Mapping[str, Parameter] = signature(function).parameters
|
| 80 |
+
|
| 81 |
+
if parameters.keys() & {ALT_V_ARGS, ALT_V_KWARGS, V_POSITIONAL_ONLY_NAME, V_DUPLICATE_KWARGS}:
|
| 82 |
+
raise PydanticUserError(
|
| 83 |
+
f'"{ALT_V_ARGS}", "{ALT_V_KWARGS}", "{V_POSITIONAL_ONLY_NAME}" and "{V_DUPLICATE_KWARGS}" '
|
| 84 |
+
f'are not permitted as argument names when using the "{validate_arguments.__name__}" decorator',
|
| 85 |
+
code=None,
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
self.raw_function = function
|
| 89 |
+
self.arg_mapping: Dict[int, str] = {}
|
| 90 |
+
self.positional_only_args: set[str] = set()
|
| 91 |
+
self.v_args_name = 'args'
|
| 92 |
+
self.v_kwargs_name = 'kwargs'
|
| 93 |
+
|
| 94 |
+
type_hints = _typing_extra.get_type_hints(function, include_extras=True)
|
| 95 |
+
takes_args = False
|
| 96 |
+
takes_kwargs = False
|
| 97 |
+
fields: Dict[str, Tuple[Any, Any]] = {}
|
| 98 |
+
for i, (name, p) in enumerate(parameters.items()):
|
| 99 |
+
if p.annotation is p.empty:
|
| 100 |
+
annotation = Any
|
| 101 |
+
else:
|
| 102 |
+
annotation = type_hints[name]
|
| 103 |
+
|
| 104 |
+
default = ... if p.default is p.empty else p.default
|
| 105 |
+
if p.kind == Parameter.POSITIONAL_ONLY:
|
| 106 |
+
self.arg_mapping[i] = name
|
| 107 |
+
fields[name] = annotation, default
|
| 108 |
+
fields[V_POSITIONAL_ONLY_NAME] = List[str], None
|
| 109 |
+
self.positional_only_args.add(name)
|
| 110 |
+
elif p.kind == Parameter.POSITIONAL_OR_KEYWORD:
|
| 111 |
+
self.arg_mapping[i] = name
|
| 112 |
+
fields[name] = annotation, default
|
| 113 |
+
fields[V_DUPLICATE_KWARGS] = List[str], None
|
| 114 |
+
elif p.kind == Parameter.KEYWORD_ONLY:
|
| 115 |
+
fields[name] = annotation, default
|
| 116 |
+
elif p.kind == Parameter.VAR_POSITIONAL:
|
| 117 |
+
self.v_args_name = name
|
| 118 |
+
fields[name] = Tuple[annotation, ...], None
|
| 119 |
+
takes_args = True
|
| 120 |
+
else:
|
| 121 |
+
assert p.kind == Parameter.VAR_KEYWORD, p.kind
|
| 122 |
+
self.v_kwargs_name = name
|
| 123 |
+
fields[name] = Dict[str, annotation], None
|
| 124 |
+
takes_kwargs = True
|
| 125 |
+
|
| 126 |
+
# these checks avoid a clash between "args" and a field with that name
|
| 127 |
+
if not takes_args and self.v_args_name in fields:
|
| 128 |
+
self.v_args_name = ALT_V_ARGS
|
| 129 |
+
|
| 130 |
+
# same with "kwargs"
|
| 131 |
+
if not takes_kwargs and self.v_kwargs_name in fields:
|
| 132 |
+
self.v_kwargs_name = ALT_V_KWARGS
|
| 133 |
+
|
| 134 |
+
if not takes_args:
|
| 135 |
+
# we add the field so validation below can raise the correct exception
|
| 136 |
+
fields[self.v_args_name] = List[Any], None
|
| 137 |
+
|
| 138 |
+
if not takes_kwargs:
|
| 139 |
+
# same with kwargs
|
| 140 |
+
fields[self.v_kwargs_name] = Dict[Any, Any], None
|
| 141 |
+
|
| 142 |
+
self.create_model(fields, takes_args, takes_kwargs, config)
|
| 143 |
+
|
| 144 |
+
def init_model_instance(self, *args: Any, **kwargs: Any) -> BaseModel:
|
| 145 |
+
values = self.build_values(args, kwargs)
|
| 146 |
+
return self.model(**values)
|
| 147 |
+
|
| 148 |
+
def call(self, *args: Any, **kwargs: Any) -> Any:
|
| 149 |
+
m = self.init_model_instance(*args, **kwargs)
|
| 150 |
+
return self.execute(m)
|
| 151 |
+
|
| 152 |
+
def build_values(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Dict[str, Any]:
|
| 153 |
+
values: Dict[str, Any] = {}
|
| 154 |
+
if args:
|
| 155 |
+
arg_iter = enumerate(args)
|
| 156 |
+
while True:
|
| 157 |
+
try:
|
| 158 |
+
i, a = next(arg_iter)
|
| 159 |
+
except StopIteration:
|
| 160 |
+
break
|
| 161 |
+
arg_name = self.arg_mapping.get(i)
|
| 162 |
+
if arg_name is not None:
|
| 163 |
+
values[arg_name] = a
|
| 164 |
+
else:
|
| 165 |
+
values[self.v_args_name] = [a] + [a for _, a in arg_iter]
|
| 166 |
+
break
|
| 167 |
+
|
| 168 |
+
var_kwargs: Dict[str, Any] = {}
|
| 169 |
+
wrong_positional_args = []
|
| 170 |
+
duplicate_kwargs = []
|
| 171 |
+
fields_alias = [
|
| 172 |
+
field.alias
|
| 173 |
+
for name, field in self.model.__pydantic_fields__.items()
|
| 174 |
+
if name not in (self.v_args_name, self.v_kwargs_name)
|
| 175 |
+
]
|
| 176 |
+
non_var_fields = set(self.model.__pydantic_fields__) - {self.v_args_name, self.v_kwargs_name}
|
| 177 |
+
for k, v in kwargs.items():
|
| 178 |
+
if k in non_var_fields or k in fields_alias:
|
| 179 |
+
if k in self.positional_only_args:
|
| 180 |
+
wrong_positional_args.append(k)
|
| 181 |
+
if k in values:
|
| 182 |
+
duplicate_kwargs.append(k)
|
| 183 |
+
values[k] = v
|
| 184 |
+
else:
|
| 185 |
+
var_kwargs[k] = v
|
| 186 |
+
|
| 187 |
+
if var_kwargs:
|
| 188 |
+
values[self.v_kwargs_name] = var_kwargs
|
| 189 |
+
if wrong_positional_args:
|
| 190 |
+
values[V_POSITIONAL_ONLY_NAME] = wrong_positional_args
|
| 191 |
+
if duplicate_kwargs:
|
| 192 |
+
values[V_DUPLICATE_KWARGS] = duplicate_kwargs
|
| 193 |
+
return values
|
| 194 |
+
|
| 195 |
+
def execute(self, m: BaseModel) -> Any:
|
| 196 |
+
d = {
|
| 197 |
+
k: v
|
| 198 |
+
for k, v in m.__dict__.items()
|
| 199 |
+
if k in m.__pydantic_fields_set__ or m.__pydantic_fields__[k].default_factory
|
| 200 |
+
}
|
| 201 |
+
var_kwargs = d.pop(self.v_kwargs_name, {})
|
| 202 |
+
|
| 203 |
+
if self.v_args_name in d:
|
| 204 |
+
args_: List[Any] = []
|
| 205 |
+
in_kwargs = False
|
| 206 |
+
kwargs = {}
|
| 207 |
+
for name, value in d.items():
|
| 208 |
+
if in_kwargs:
|
| 209 |
+
kwargs[name] = value
|
| 210 |
+
elif name == self.v_args_name:
|
| 211 |
+
args_ += value
|
| 212 |
+
in_kwargs = True
|
| 213 |
+
else:
|
| 214 |
+
args_.append(value)
|
| 215 |
+
return self.raw_function(*args_, **kwargs, **var_kwargs)
|
| 216 |
+
elif self.positional_only_args:
|
| 217 |
+
args_ = []
|
| 218 |
+
kwargs = {}
|
| 219 |
+
for name, value in d.items():
|
| 220 |
+
if name in self.positional_only_args:
|
| 221 |
+
args_.append(value)
|
| 222 |
+
else:
|
| 223 |
+
kwargs[name] = value
|
| 224 |
+
return self.raw_function(*args_, **kwargs, **var_kwargs)
|
| 225 |
+
else:
|
| 226 |
+
return self.raw_function(**d, **var_kwargs)
|
| 227 |
+
|
| 228 |
+
def create_model(self, fields: Dict[str, Any], takes_args: bool, takes_kwargs: bool, config: 'ConfigType') -> None:
|
| 229 |
+
pos_args = len(self.arg_mapping)
|
| 230 |
+
|
| 231 |
+
config_wrapper = _config.ConfigWrapper(config)
|
| 232 |
+
|
| 233 |
+
if config_wrapper.alias_generator:
|
| 234 |
+
raise PydanticUserError(
|
| 235 |
+
'Setting the "alias_generator" property on custom Config for '
|
| 236 |
+
'@validate_arguments is not yet supported, please remove.',
|
| 237 |
+
code=None,
|
| 238 |
+
)
|
| 239 |
+
if config_wrapper.extra is None:
|
| 240 |
+
config_wrapper.config_dict['extra'] = 'forbid'
|
| 241 |
+
|
| 242 |
+
class DecoratorBaseModel(BaseModel):
|
| 243 |
+
@field_validator(self.v_args_name, check_fields=False)
|
| 244 |
+
@classmethod
|
| 245 |
+
def check_args(cls, v: Optional[List[Any]]) -> Optional[List[Any]]:
|
| 246 |
+
if takes_args or v is None:
|
| 247 |
+
return v
|
| 248 |
+
|
| 249 |
+
raise TypeError(f'{pos_args} positional arguments expected but {pos_args + len(v)} given')
|
| 250 |
+
|
| 251 |
+
@field_validator(self.v_kwargs_name, check_fields=False)
|
| 252 |
+
@classmethod
|
| 253 |
+
def check_kwargs(cls, v: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
| 254 |
+
if takes_kwargs or v is None:
|
| 255 |
+
return v
|
| 256 |
+
|
| 257 |
+
plural = '' if len(v) == 1 else 's'
|
| 258 |
+
keys = ', '.join(map(repr, v.keys()))
|
| 259 |
+
raise TypeError(f'unexpected keyword argument{plural}: {keys}')
|
| 260 |
+
|
| 261 |
+
@field_validator(V_POSITIONAL_ONLY_NAME, check_fields=False)
|
| 262 |
+
@classmethod
|
| 263 |
+
def check_positional_only(cls, v: Optional[List[str]]) -> None:
|
| 264 |
+
if v is None:
|
| 265 |
+
return
|
| 266 |
+
|
| 267 |
+
plural = '' if len(v) == 1 else 's'
|
| 268 |
+
keys = ', '.join(map(repr, v))
|
| 269 |
+
raise TypeError(f'positional-only argument{plural} passed as keyword argument{plural}: {keys}')
|
| 270 |
+
|
| 271 |
+
@field_validator(V_DUPLICATE_KWARGS, check_fields=False)
|
| 272 |
+
@classmethod
|
| 273 |
+
def check_duplicate_kwargs(cls, v: Optional[List[str]]) -> None:
|
| 274 |
+
if v is None:
|
| 275 |
+
return
|
| 276 |
+
|
| 277 |
+
plural = '' if len(v) == 1 else 's'
|
| 278 |
+
keys = ', '.join(map(repr, v))
|
| 279 |
+
raise TypeError(f'multiple values for argument{plural}: {keys}')
|
| 280 |
+
|
| 281 |
+
model_config = config_wrapper.config_dict
|
| 282 |
+
|
| 283 |
+
self.model = create_model(to_pascal(self.raw_function.__name__), __base__=DecoratorBaseModel, **fields)
|
vllm/lib/python3.10/site-packages/pydantic/deprecated/json.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import datetime
|
| 2 |
+
import warnings
|
| 3 |
+
from collections import deque
|
| 4 |
+
from decimal import Decimal
|
| 5 |
+
from enum import Enum
|
| 6 |
+
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from re import Pattern
|
| 9 |
+
from types import GeneratorType
|
| 10 |
+
from typing import TYPE_CHECKING, Any, Callable, Dict, Type, Union
|
| 11 |
+
from uuid import UUID
|
| 12 |
+
|
| 13 |
+
from typing_extensions import deprecated
|
| 14 |
+
|
| 15 |
+
from .._internal._import_utils import import_cached_base_model
|
| 16 |
+
from ..color import Color
|
| 17 |
+
from ..networks import NameEmail
|
| 18 |
+
from ..types import SecretBytes, SecretStr
|
| 19 |
+
from ..warnings import PydanticDeprecatedSince20
|
| 20 |
+
|
| 21 |
+
if not TYPE_CHECKING:
|
| 22 |
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
| 23 |
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
| 24 |
+
DeprecationWarning = PydanticDeprecatedSince20
|
| 25 |
+
|
| 26 |
+
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
|
| 30 |
+
return o.isoformat()
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
|
| 34 |
+
"""Encodes a Decimal as int of there's no exponent, otherwise float.
|
| 35 |
+
|
| 36 |
+
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
|
| 37 |
+
where a integer (but not int typed) is used. Encoding this as a float
|
| 38 |
+
results in failed round-tripping between encode and parse.
|
| 39 |
+
Our Id type is a prime example of this.
|
| 40 |
+
|
| 41 |
+
>>> decimal_encoder(Decimal("1.0"))
|
| 42 |
+
1.0
|
| 43 |
+
|
| 44 |
+
>>> decimal_encoder(Decimal("1"))
|
| 45 |
+
1
|
| 46 |
+
"""
|
| 47 |
+
exponent = dec_value.as_tuple().exponent
|
| 48 |
+
if isinstance(exponent, int) and exponent >= 0:
|
| 49 |
+
return int(dec_value)
|
| 50 |
+
else:
|
| 51 |
+
return float(dec_value)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
|
| 55 |
+
bytes: lambda o: o.decode(),
|
| 56 |
+
Color: str,
|
| 57 |
+
datetime.date: isoformat,
|
| 58 |
+
datetime.datetime: isoformat,
|
| 59 |
+
datetime.time: isoformat,
|
| 60 |
+
datetime.timedelta: lambda td: td.total_seconds(),
|
| 61 |
+
Decimal: decimal_encoder,
|
| 62 |
+
Enum: lambda o: o.value,
|
| 63 |
+
frozenset: list,
|
| 64 |
+
deque: list,
|
| 65 |
+
GeneratorType: list,
|
| 66 |
+
IPv4Address: str,
|
| 67 |
+
IPv4Interface: str,
|
| 68 |
+
IPv4Network: str,
|
| 69 |
+
IPv6Address: str,
|
| 70 |
+
IPv6Interface: str,
|
| 71 |
+
IPv6Network: str,
|
| 72 |
+
NameEmail: str,
|
| 73 |
+
Path: str,
|
| 74 |
+
Pattern: lambda o: o.pattern,
|
| 75 |
+
SecretBytes: str,
|
| 76 |
+
SecretStr: str,
|
| 77 |
+
set: list,
|
| 78 |
+
UUID: str,
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@deprecated(
|
| 83 |
+
'`pydantic_encoder` is deprecated, use `pydantic_core.to_jsonable_python` instead.',
|
| 84 |
+
category=None,
|
| 85 |
+
)
|
| 86 |
+
def pydantic_encoder(obj: Any) -> Any:
|
| 87 |
+
warnings.warn(
|
| 88 |
+
'`pydantic_encoder` is deprecated, use `pydantic_core.to_jsonable_python` instead.',
|
| 89 |
+
category=PydanticDeprecatedSince20,
|
| 90 |
+
stacklevel=2,
|
| 91 |
+
)
|
| 92 |
+
from dataclasses import asdict, is_dataclass
|
| 93 |
+
|
| 94 |
+
BaseModel = import_cached_base_model()
|
| 95 |
+
|
| 96 |
+
if isinstance(obj, BaseModel):
|
| 97 |
+
return obj.model_dump()
|
| 98 |
+
elif is_dataclass(obj):
|
| 99 |
+
return asdict(obj) # type: ignore
|
| 100 |
+
|
| 101 |
+
# Check the class type and its superclasses for a matching encoder
|
| 102 |
+
for base in obj.__class__.__mro__[:-1]:
|
| 103 |
+
try:
|
| 104 |
+
encoder = ENCODERS_BY_TYPE[base]
|
| 105 |
+
except KeyError:
|
| 106 |
+
continue
|
| 107 |
+
return encoder(obj)
|
| 108 |
+
else: # We have exited the for loop without finding a suitable encoder
|
| 109 |
+
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# TODO: Add a suggested migration path once there is a way to use custom encoders
|
| 113 |
+
@deprecated(
|
| 114 |
+
'`custom_pydantic_encoder` is deprecated, use `BaseModel.model_dump` instead.',
|
| 115 |
+
category=None,
|
| 116 |
+
)
|
| 117 |
+
def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
|
| 118 |
+
warnings.warn(
|
| 119 |
+
'`custom_pydantic_encoder` is deprecated, use `BaseModel.model_dump` instead.',
|
| 120 |
+
category=PydanticDeprecatedSince20,
|
| 121 |
+
stacklevel=2,
|
| 122 |
+
)
|
| 123 |
+
# Check the class type and its superclasses for a matching encoder
|
| 124 |
+
for base in obj.__class__.__mro__[:-1]:
|
| 125 |
+
try:
|
| 126 |
+
encoder = type_encoders[base]
|
| 127 |
+
except KeyError:
|
| 128 |
+
continue
|
| 129 |
+
|
| 130 |
+
return encoder(obj)
|
| 131 |
+
else: # We have exited the for loop without finding a suitable encoder
|
| 132 |
+
return pydantic_encoder(obj)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@deprecated('`timedelta_isoformat` is deprecated.', category=None)
|
| 136 |
+
def timedelta_isoformat(td: datetime.timedelta) -> str:
|
| 137 |
+
"""ISO 8601 encoding for Python timedelta object."""
|
| 138 |
+
warnings.warn('`timedelta_isoformat` is deprecated.', category=PydanticDeprecatedSince20, stacklevel=2)
|
| 139 |
+
minutes, seconds = divmod(td.seconds, 60)
|
| 140 |
+
hours, minutes = divmod(minutes, 60)
|
| 141 |
+
return f'{"-" if td.days < 0 else ""}P{abs(td.days)}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
|
vllm/lib/python3.10/site-packages/pydantic/deprecated/parse.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import pickle
|
| 5 |
+
import warnings
|
| 6 |
+
from enum import Enum
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import TYPE_CHECKING, Any, Callable
|
| 9 |
+
|
| 10 |
+
from typing_extensions import deprecated
|
| 11 |
+
|
| 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 |
+
|
| 20 |
+
class Protocol(str, Enum):
|
| 21 |
+
json = 'json'
|
| 22 |
+
pickle = 'pickle'
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@deprecated('`load_str_bytes` is deprecated.', category=None)
|
| 26 |
+
def load_str_bytes(
|
| 27 |
+
b: str | bytes,
|
| 28 |
+
*,
|
| 29 |
+
content_type: str | None = None,
|
| 30 |
+
encoding: str = 'utf8',
|
| 31 |
+
proto: Protocol | None = None,
|
| 32 |
+
allow_pickle: bool = False,
|
| 33 |
+
json_loads: Callable[[str], Any] = json.loads,
|
| 34 |
+
) -> Any:
|
| 35 |
+
warnings.warn('`load_str_bytes` is deprecated.', category=PydanticDeprecatedSince20, stacklevel=2)
|
| 36 |
+
if proto is None and content_type:
|
| 37 |
+
if content_type.endswith(('json', 'javascript')):
|
| 38 |
+
pass
|
| 39 |
+
elif allow_pickle and content_type.endswith('pickle'):
|
| 40 |
+
proto = Protocol.pickle
|
| 41 |
+
else:
|
| 42 |
+
raise TypeError(f'Unknown content-type: {content_type}')
|
| 43 |
+
|
| 44 |
+
proto = proto or Protocol.json
|
| 45 |
+
|
| 46 |
+
if proto == Protocol.json:
|
| 47 |
+
if isinstance(b, bytes):
|
| 48 |
+
b = b.decode(encoding)
|
| 49 |
+
return json_loads(b) # type: ignore
|
| 50 |
+
elif proto == Protocol.pickle:
|
| 51 |
+
if not allow_pickle:
|
| 52 |
+
raise RuntimeError('Trying to decode with pickle with allow_pickle=False')
|
| 53 |
+
bb = b if isinstance(b, bytes) else b.encode() # type: ignore
|
| 54 |
+
return pickle.loads(bb)
|
| 55 |
+
else:
|
| 56 |
+
raise TypeError(f'Unknown protocol: {proto}')
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@deprecated('`load_file` is deprecated.', category=None)
|
| 60 |
+
def load_file(
|
| 61 |
+
path: str | Path,
|
| 62 |
+
*,
|
| 63 |
+
content_type: str | None = None,
|
| 64 |
+
encoding: str = 'utf8',
|
| 65 |
+
proto: Protocol | None = None,
|
| 66 |
+
allow_pickle: bool = False,
|
| 67 |
+
json_loads: Callable[[str], Any] = json.loads,
|
| 68 |
+
) -> Any:
|
| 69 |
+
warnings.warn('`load_file` is deprecated.', category=PydanticDeprecatedSince20, stacklevel=2)
|
| 70 |
+
path = Path(path)
|
| 71 |
+
b = path.read_bytes()
|
| 72 |
+
if content_type is None:
|
| 73 |
+
if path.suffix in ('.js', '.json'):
|
| 74 |
+
proto = Protocol.json
|
| 75 |
+
elif path.suffix == '.pkl':
|
| 76 |
+
proto = Protocol.pickle
|
| 77 |
+
|
| 78 |
+
return load_str_bytes(
|
| 79 |
+
b, proto=proto, content_type=content_type, encoding=encoding, allow_pickle=allow_pickle, json_loads=json_loads
|
| 80 |
+
)
|
vllm/lib/python3.10/site-packages/pydantic/deprecated/tools.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import warnings
|
| 5 |
+
from typing import TYPE_CHECKING, Any, Callable, Type, TypeVar, Union
|
| 6 |
+
|
| 7 |
+
from typing_extensions import deprecated
|
| 8 |
+
|
| 9 |
+
from ..json_schema import DEFAULT_REF_TEMPLATE, GenerateJsonSchema
|
| 10 |
+
from ..type_adapter import TypeAdapter
|
| 11 |
+
from ..warnings import PydanticDeprecatedSince20
|
| 12 |
+
|
| 13 |
+
if not TYPE_CHECKING:
|
| 14 |
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
| 15 |
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
| 16 |
+
DeprecationWarning = PydanticDeprecatedSince20
|
| 17 |
+
|
| 18 |
+
__all__ = 'parse_obj_as', 'schema_of', 'schema_json_of'
|
| 19 |
+
|
| 20 |
+
NameFactory = Union[str, Callable[[Type[Any]], str]]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
T = TypeVar('T')
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@deprecated(
|
| 27 |
+
'`parse_obj_as` is deprecated. Use `pydantic.TypeAdapter.validate_python` instead.',
|
| 28 |
+
category=None,
|
| 29 |
+
)
|
| 30 |
+
def parse_obj_as(type_: type[T], obj: Any, type_name: NameFactory | None = None) -> T:
|
| 31 |
+
warnings.warn(
|
| 32 |
+
'`parse_obj_as` is deprecated. Use `pydantic.TypeAdapter.validate_python` instead.',
|
| 33 |
+
category=PydanticDeprecatedSince20,
|
| 34 |
+
stacklevel=2,
|
| 35 |
+
)
|
| 36 |
+
if type_name is not None: # pragma: no cover
|
| 37 |
+
warnings.warn(
|
| 38 |
+
'The type_name parameter is deprecated. parse_obj_as no longer creates temporary models',
|
| 39 |
+
DeprecationWarning,
|
| 40 |
+
stacklevel=2,
|
| 41 |
+
)
|
| 42 |
+
return TypeAdapter(type_).validate_python(obj)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@deprecated(
|
| 46 |
+
'`schema_of` is deprecated. Use `pydantic.TypeAdapter.json_schema` instead.',
|
| 47 |
+
category=None,
|
| 48 |
+
)
|
| 49 |
+
def schema_of(
|
| 50 |
+
type_: Any,
|
| 51 |
+
*,
|
| 52 |
+
title: NameFactory | None = None,
|
| 53 |
+
by_alias: bool = True,
|
| 54 |
+
ref_template: str = DEFAULT_REF_TEMPLATE,
|
| 55 |
+
schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
|
| 56 |
+
) -> dict[str, Any]:
|
| 57 |
+
"""Generate a JSON schema (as dict) for the passed model or dynamically generated one."""
|
| 58 |
+
warnings.warn(
|
| 59 |
+
'`schema_of` is deprecated. Use `pydantic.TypeAdapter.json_schema` instead.',
|
| 60 |
+
category=PydanticDeprecatedSince20,
|
| 61 |
+
stacklevel=2,
|
| 62 |
+
)
|
| 63 |
+
res = TypeAdapter(type_).json_schema(
|
| 64 |
+
by_alias=by_alias,
|
| 65 |
+
schema_generator=schema_generator,
|
| 66 |
+
ref_template=ref_template,
|
| 67 |
+
)
|
| 68 |
+
if title is not None:
|
| 69 |
+
if isinstance(title, str):
|
| 70 |
+
res['title'] = title
|
| 71 |
+
else:
|
| 72 |
+
warnings.warn(
|
| 73 |
+
'Passing a callable for the `title` parameter is deprecated and no longer supported',
|
| 74 |
+
DeprecationWarning,
|
| 75 |
+
stacklevel=2,
|
| 76 |
+
)
|
| 77 |
+
res['title'] = title(type_)
|
| 78 |
+
return res
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@deprecated(
|
| 82 |
+
'`schema_json_of` is deprecated. Use `pydantic.TypeAdapter.json_schema` instead.',
|
| 83 |
+
category=None,
|
| 84 |
+
)
|
| 85 |
+
def schema_json_of(
|
| 86 |
+
type_: Any,
|
| 87 |
+
*,
|
| 88 |
+
title: NameFactory | None = None,
|
| 89 |
+
by_alias: bool = True,
|
| 90 |
+
ref_template: str = DEFAULT_REF_TEMPLATE,
|
| 91 |
+
schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
|
| 92 |
+
**dumps_kwargs: Any,
|
| 93 |
+
) -> str:
|
| 94 |
+
"""Generate a JSON schema (as JSON) for the passed model or dynamically generated one."""
|
| 95 |
+
warnings.warn(
|
| 96 |
+
'`schema_json_of` is deprecated. Use `pydantic.TypeAdapter.json_schema` instead.',
|
| 97 |
+
category=PydanticDeprecatedSince20,
|
| 98 |
+
stacklevel=2,
|
| 99 |
+
)
|
| 100 |
+
return json.dumps(
|
| 101 |
+
schema_of(type_, title=title, by_alias=by_alias, ref_template=ref_template, schema_generator=schema_generator),
|
| 102 |
+
**dumps_kwargs,
|
| 103 |
+
)
|
vllm/lib/python3.10/site-packages/pydantic/env_settings.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The `env_settings` module is a backport module from V1."""
|
| 2 |
+
|
| 3 |
+
from ._migration import getattr_migration
|
| 4 |
+
|
| 5 |
+
__getattr__ = getattr_migration(__name__)
|
vllm/lib/python3.10/site-packages/pydantic/error_wrappers.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The `error_wrappers` module is a backport module from V1."""
|
| 2 |
+
|
| 3 |
+
from ._migration import getattr_migration
|
| 4 |
+
|
| 5 |
+
__getattr__ = getattr_migration(__name__)
|
vllm/lib/python3.10/site-packages/pydantic/errors.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pydantic-specific errors."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations as _annotations
|
| 4 |
+
|
| 5 |
+
import re
|
| 6 |
+
|
| 7 |
+
from typing_extensions import Literal, Self
|
| 8 |
+
|
| 9 |
+
from ._migration import getattr_migration
|
| 10 |
+
from .version import version_short
|
| 11 |
+
|
| 12 |
+
__all__ = (
|
| 13 |
+
'PydanticUserError',
|
| 14 |
+
'PydanticUndefinedAnnotation',
|
| 15 |
+
'PydanticImportError',
|
| 16 |
+
'PydanticSchemaGenerationError',
|
| 17 |
+
'PydanticInvalidForJsonSchema',
|
| 18 |
+
'PydanticErrorCodes',
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
# We use this URL to allow for future flexibility about how we host the docs, while allowing for Pydantic
|
| 22 |
+
# code in the while with "old" URLs to still work.
|
| 23 |
+
# 'u' refers to "user errors" - e.g. errors caused by developers using pydantic, as opposed to validation errors.
|
| 24 |
+
DEV_ERROR_DOCS_URL = f'https://errors.pydantic.dev/{version_short()}/u/'
|
| 25 |
+
PydanticErrorCodes = Literal[
|
| 26 |
+
'class-not-fully-defined',
|
| 27 |
+
'custom-json-schema',
|
| 28 |
+
'decorator-missing-field',
|
| 29 |
+
'discriminator-no-field',
|
| 30 |
+
'discriminator-alias-type',
|
| 31 |
+
'discriminator-needs-literal',
|
| 32 |
+
'discriminator-alias',
|
| 33 |
+
'discriminator-validator',
|
| 34 |
+
'callable-discriminator-no-tag',
|
| 35 |
+
'typed-dict-version',
|
| 36 |
+
'model-field-overridden',
|
| 37 |
+
'model-field-missing-annotation',
|
| 38 |
+
'config-both',
|
| 39 |
+
'removed-kwargs',
|
| 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 |
+
'import-error',
|
| 47 |
+
'create-model-field-definitions',
|
| 48 |
+
'create-model-config-base',
|
| 49 |
+
'validator-no-fields',
|
| 50 |
+
'validator-invalid-fields',
|
| 51 |
+
'validator-instance-method',
|
| 52 |
+
'validator-input-type',
|
| 53 |
+
'root-validator-pre-skip',
|
| 54 |
+
'model-serializer-instance-method',
|
| 55 |
+
'validator-field-config-info',
|
| 56 |
+
'validator-v1-signature',
|
| 57 |
+
'validator-signature',
|
| 58 |
+
'field-serializer-signature',
|
| 59 |
+
'model-serializer-signature',
|
| 60 |
+
'multiple-field-serializers',
|
| 61 |
+
'invalid-annotated-type',
|
| 62 |
+
'type-adapter-config-unused',
|
| 63 |
+
'root-model-extra',
|
| 64 |
+
'unevaluable-type-annotation',
|
| 65 |
+
'dataclass-init-false-extra-allow',
|
| 66 |
+
'clashing-init-and-init-var',
|
| 67 |
+
'model-config-invalid-field-name',
|
| 68 |
+
'with-config-on-model',
|
| 69 |
+
'dataclass-on-model',
|
| 70 |
+
'validate-call-type',
|
| 71 |
+
'unpack-typed-dict',
|
| 72 |
+
'overlapping-unpack-typed-dict',
|
| 73 |
+
'invalid-self-type',
|
| 74 |
+
]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class PydanticErrorMixin:
|
| 78 |
+
"""A mixin class for common functionality shared by all Pydantic-specific errors.
|
| 79 |
+
|
| 80 |
+
Attributes:
|
| 81 |
+
message: A message describing the error.
|
| 82 |
+
code: An optional error code from PydanticErrorCodes enum.
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
def __init__(self, message: str, *, code: PydanticErrorCodes | None) -> None:
|
| 86 |
+
self.message = message
|
| 87 |
+
self.code = code
|
| 88 |
+
|
| 89 |
+
def __str__(self) -> str:
|
| 90 |
+
if self.code is None:
|
| 91 |
+
return self.message
|
| 92 |
+
else:
|
| 93 |
+
return f'{self.message}\n\nFor further information visit {DEV_ERROR_DOCS_URL}{self.code}'
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class PydanticUserError(PydanticErrorMixin, TypeError):
|
| 97 |
+
"""An error raised due to incorrect use of Pydantic."""
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class PydanticUndefinedAnnotation(PydanticErrorMixin, NameError):
|
| 101 |
+
"""A subclass of `NameError` raised when handling undefined annotations during `CoreSchema` generation.
|
| 102 |
+
|
| 103 |
+
Attributes:
|
| 104 |
+
name: Name of the error.
|
| 105 |
+
message: Description of the error.
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
def __init__(self, name: str, message: str) -> None:
|
| 109 |
+
self.name = name
|
| 110 |
+
super().__init__(message=message, code='undefined-annotation')
|
| 111 |
+
|
| 112 |
+
@classmethod
|
| 113 |
+
def from_name_error(cls, name_error: NameError) -> Self:
|
| 114 |
+
"""Convert a `NameError` to a `PydanticUndefinedAnnotation` error.
|
| 115 |
+
|
| 116 |
+
Args:
|
| 117 |
+
name_error: `NameError` to be converted.
|
| 118 |
+
|
| 119 |
+
Returns:
|
| 120 |
+
Converted `PydanticUndefinedAnnotation` error.
|
| 121 |
+
"""
|
| 122 |
+
try:
|
| 123 |
+
name = name_error.name # type: ignore # python > 3.10
|
| 124 |
+
except AttributeError:
|
| 125 |
+
name = re.search(r".*'(.+?)'", str(name_error)).group(1) # type: ignore[union-attr]
|
| 126 |
+
return cls(name=name, message=str(name_error))
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class PydanticImportError(PydanticErrorMixin, ImportError):
|
| 130 |
+
"""An error raised when an import fails due to module changes between V1 and V2.
|
| 131 |
+
|
| 132 |
+
Attributes:
|
| 133 |
+
message: Description of the error.
|
| 134 |
+
"""
|
| 135 |
+
|
| 136 |
+
def __init__(self, message: str) -> None:
|
| 137 |
+
super().__init__(message, code='import-error')
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class PydanticSchemaGenerationError(PydanticUserError):
|
| 141 |
+
"""An error raised during failures to generate a `CoreSchema` for some type.
|
| 142 |
+
|
| 143 |
+
Attributes:
|
| 144 |
+
message: Description of the error.
|
| 145 |
+
"""
|
| 146 |
+
|
| 147 |
+
def __init__(self, message: str) -> None:
|
| 148 |
+
super().__init__(message, code='schema-for-unknown-type')
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class PydanticInvalidForJsonSchema(PydanticUserError):
|
| 152 |
+
"""An error raised during failures to generate a JSON schema for some `CoreSchema`.
|
| 153 |
+
|
| 154 |
+
Attributes:
|
| 155 |
+
message: Description of the error.
|
| 156 |
+
"""
|
| 157 |
+
|
| 158 |
+
def __init__(self, message: str) -> None:
|
| 159 |
+
super().__init__(message, code='invalid-for-json-schema')
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
__getattr__ = getattr_migration(__name__)
|
vllm/lib/python3.10/site-packages/pydantic/experimental/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The "experimental" module of pydantic contains potential new features that are subject to change."""
|
| 2 |
+
|
| 3 |
+
import warnings
|
| 4 |
+
|
| 5 |
+
from pydantic.warnings import PydanticExperimentalWarning
|
| 6 |
+
|
| 7 |
+
warnings.warn(
|
| 8 |
+
'This module is experimental, its contents are subject to change and deprecation.',
|
| 9 |
+
category=PydanticExperimentalWarning,
|
| 10 |
+
)
|
vllm/lib/python3.10/site-packages/pydantic/experimental/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (496 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/pydantic/experimental/__pycache__/pipeline.cpython-310.pyc
ADDED
|
Binary file (23.2 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/pydantic/experimental/pipeline.py
ADDED
|
@@ -0,0 +1,669 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Experimental pipeline API functionality. Be careful with this API, it's subject to change."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import datetime
|
| 6 |
+
import operator
|
| 7 |
+
import re
|
| 8 |
+
import sys
|
| 9 |
+
from collections import deque
|
| 10 |
+
from collections.abc import Container
|
| 11 |
+
from dataclasses import dataclass
|
| 12 |
+
from decimal import Decimal
|
| 13 |
+
from functools import cached_property, partial
|
| 14 |
+
from typing import TYPE_CHECKING, Any, Callable, Generic, Pattern, Protocol, TypeVar, Union, overload
|
| 15 |
+
|
| 16 |
+
import annotated_types
|
| 17 |
+
from typing_extensions import Annotated
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from pydantic_core import core_schema as cs
|
| 21 |
+
|
| 22 |
+
from pydantic import GetCoreSchemaHandler
|
| 23 |
+
|
| 24 |
+
from pydantic._internal._internal_dataclass import slots_true as _slots_true
|
| 25 |
+
|
| 26 |
+
if sys.version_info < (3, 10):
|
| 27 |
+
EllipsisType = type(Ellipsis)
|
| 28 |
+
else:
|
| 29 |
+
from types import EllipsisType
|
| 30 |
+
|
| 31 |
+
__all__ = ['validate_as', 'validate_as_deferred', 'transform']
|
| 32 |
+
|
| 33 |
+
_slots_frozen = {**_slots_true, 'frozen': True}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@dataclass(**_slots_frozen)
|
| 37 |
+
class _ValidateAs:
|
| 38 |
+
tp: type[Any]
|
| 39 |
+
strict: bool = False
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@dataclass
|
| 43 |
+
class _ValidateAsDefer:
|
| 44 |
+
func: Callable[[], type[Any]]
|
| 45 |
+
|
| 46 |
+
@cached_property
|
| 47 |
+
def tp(self) -> type[Any]:
|
| 48 |
+
return self.func()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@dataclass(**_slots_frozen)
|
| 52 |
+
class _Transform:
|
| 53 |
+
func: Callable[[Any], Any]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@dataclass(**_slots_frozen)
|
| 57 |
+
class _PipelineOr:
|
| 58 |
+
left: _Pipeline[Any, Any]
|
| 59 |
+
right: _Pipeline[Any, Any]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@dataclass(**_slots_frozen)
|
| 63 |
+
class _PipelineAnd:
|
| 64 |
+
left: _Pipeline[Any, Any]
|
| 65 |
+
right: _Pipeline[Any, Any]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@dataclass(**_slots_frozen)
|
| 69 |
+
class _Eq:
|
| 70 |
+
value: Any
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@dataclass(**_slots_frozen)
|
| 74 |
+
class _NotEq:
|
| 75 |
+
value: Any
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@dataclass(**_slots_frozen)
|
| 79 |
+
class _In:
|
| 80 |
+
values: Container[Any]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@dataclass(**_slots_frozen)
|
| 84 |
+
class _NotIn:
|
| 85 |
+
values: Container[Any]
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
_ConstraintAnnotation = Union[
|
| 89 |
+
annotated_types.Le,
|
| 90 |
+
annotated_types.Ge,
|
| 91 |
+
annotated_types.Lt,
|
| 92 |
+
annotated_types.Gt,
|
| 93 |
+
annotated_types.Len,
|
| 94 |
+
annotated_types.MultipleOf,
|
| 95 |
+
annotated_types.Timezone,
|
| 96 |
+
annotated_types.Interval,
|
| 97 |
+
annotated_types.Predicate,
|
| 98 |
+
# common predicates not included in annotated_types
|
| 99 |
+
_Eq,
|
| 100 |
+
_NotEq,
|
| 101 |
+
_In,
|
| 102 |
+
_NotIn,
|
| 103 |
+
# regular expressions
|
| 104 |
+
Pattern[str],
|
| 105 |
+
]
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@dataclass(**_slots_frozen)
|
| 109 |
+
class _Constraint:
|
| 110 |
+
constraint: _ConstraintAnnotation
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
_Step = Union[_ValidateAs, _ValidateAsDefer, _Transform, _PipelineOr, _PipelineAnd, _Constraint]
|
| 114 |
+
|
| 115 |
+
_InT = TypeVar('_InT')
|
| 116 |
+
_OutT = TypeVar('_OutT')
|
| 117 |
+
_NewOutT = TypeVar('_NewOutT')
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class _FieldTypeMarker:
|
| 121 |
+
pass
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
# TODO: ultimately, make this public, see https://github.com/pydantic/pydantic/pull/9459#discussion_r1628197626
|
| 125 |
+
# Also, make this frozen eventually, but that doesn't work right now because of the generic base
|
| 126 |
+
# Which attempts to modify __orig_base__ and such.
|
| 127 |
+
# We could go with a manual freeze, but that seems overkill for now.
|
| 128 |
+
@dataclass(**_slots_true)
|
| 129 |
+
class _Pipeline(Generic[_InT, _OutT]):
|
| 130 |
+
"""Abstract representation of a chain of validation, transformation, and parsing steps."""
|
| 131 |
+
|
| 132 |
+
_steps: tuple[_Step, ...]
|
| 133 |
+
|
| 134 |
+
def transform(
|
| 135 |
+
self,
|
| 136 |
+
func: Callable[[_OutT], _NewOutT],
|
| 137 |
+
) -> _Pipeline[_InT, _NewOutT]:
|
| 138 |
+
"""Transform the output of the previous step.
|
| 139 |
+
|
| 140 |
+
If used as the first step in a pipeline, the type of the field is used.
|
| 141 |
+
That is, the transformation is applied to after the value is parsed to the field's type.
|
| 142 |
+
"""
|
| 143 |
+
return _Pipeline[_InT, _NewOutT](self._steps + (_Transform(func),))
|
| 144 |
+
|
| 145 |
+
@overload
|
| 146 |
+
def validate_as(self, tp: type[_NewOutT], *, strict: bool = ...) -> _Pipeline[_InT, _NewOutT]: ...
|
| 147 |
+
|
| 148 |
+
@overload
|
| 149 |
+
def validate_as(self, tp: EllipsisType, *, strict: bool = ...) -> _Pipeline[_InT, Any]: # type: ignore
|
| 150 |
+
...
|
| 151 |
+
|
| 152 |
+
def validate_as(self, tp: type[_NewOutT] | EllipsisType, *, strict: bool = False) -> _Pipeline[_InT, Any]: # type: ignore
|
| 153 |
+
"""Validate / parse the input into a new type.
|
| 154 |
+
|
| 155 |
+
If no type is provided, the type of the field is used.
|
| 156 |
+
|
| 157 |
+
Types are parsed in Pydantic's `lax` mode by default,
|
| 158 |
+
but you can enable `strict` mode by passing `strict=True`.
|
| 159 |
+
"""
|
| 160 |
+
if isinstance(tp, EllipsisType):
|
| 161 |
+
return _Pipeline[_InT, Any](self._steps + (_ValidateAs(_FieldTypeMarker, strict=strict),))
|
| 162 |
+
return _Pipeline[_InT, _NewOutT](self._steps + (_ValidateAs(tp, strict=strict),))
|
| 163 |
+
|
| 164 |
+
def validate_as_deferred(self, func: Callable[[], type[_NewOutT]]) -> _Pipeline[_InT, _NewOutT]:
|
| 165 |
+
"""Parse the input into a new type, deferring resolution of the type until the current class
|
| 166 |
+
is fully defined.
|
| 167 |
+
|
| 168 |
+
This is useful when you need to reference the class in it's own type annotations.
|
| 169 |
+
"""
|
| 170 |
+
return _Pipeline[_InT, _NewOutT](self._steps + (_ValidateAsDefer(func),))
|
| 171 |
+
|
| 172 |
+
# constraints
|
| 173 |
+
@overload
|
| 174 |
+
def constrain(self: _Pipeline[_InT, _NewOutGe], constraint: annotated_types.Ge) -> _Pipeline[_InT, _NewOutGe]: ...
|
| 175 |
+
|
| 176 |
+
@overload
|
| 177 |
+
def constrain(self: _Pipeline[_InT, _NewOutGt], constraint: annotated_types.Gt) -> _Pipeline[_InT, _NewOutGt]: ...
|
| 178 |
+
|
| 179 |
+
@overload
|
| 180 |
+
def constrain(self: _Pipeline[_InT, _NewOutLe], constraint: annotated_types.Le) -> _Pipeline[_InT, _NewOutLe]: ...
|
| 181 |
+
|
| 182 |
+
@overload
|
| 183 |
+
def constrain(self: _Pipeline[_InT, _NewOutLt], constraint: annotated_types.Lt) -> _Pipeline[_InT, _NewOutLt]: ...
|
| 184 |
+
|
| 185 |
+
@overload
|
| 186 |
+
def constrain(
|
| 187 |
+
self: _Pipeline[_InT, _NewOutLen], constraint: annotated_types.Len
|
| 188 |
+
) -> _Pipeline[_InT, _NewOutLen]: ...
|
| 189 |
+
|
| 190 |
+
@overload
|
| 191 |
+
def constrain(
|
| 192 |
+
self: _Pipeline[_InT, _NewOutT], constraint: annotated_types.MultipleOf
|
| 193 |
+
) -> _Pipeline[_InT, _NewOutT]: ...
|
| 194 |
+
|
| 195 |
+
@overload
|
| 196 |
+
def constrain(
|
| 197 |
+
self: _Pipeline[_InT, _NewOutDatetime], constraint: annotated_types.Timezone
|
| 198 |
+
) -> _Pipeline[_InT, _NewOutDatetime]: ...
|
| 199 |
+
|
| 200 |
+
@overload
|
| 201 |
+
def constrain(self: _Pipeline[_InT, _OutT], constraint: annotated_types.Predicate) -> _Pipeline[_InT, _OutT]: ...
|
| 202 |
+
|
| 203 |
+
@overload
|
| 204 |
+
def constrain(
|
| 205 |
+
self: _Pipeline[_InT, _NewOutInterval], constraint: annotated_types.Interval
|
| 206 |
+
) -> _Pipeline[_InT, _NewOutInterval]: ...
|
| 207 |
+
|
| 208 |
+
@overload
|
| 209 |
+
def constrain(self: _Pipeline[_InT, _OutT], constraint: _Eq) -> _Pipeline[_InT, _OutT]: ...
|
| 210 |
+
|
| 211 |
+
@overload
|
| 212 |
+
def constrain(self: _Pipeline[_InT, _OutT], constraint: _NotEq) -> _Pipeline[_InT, _OutT]: ...
|
| 213 |
+
|
| 214 |
+
@overload
|
| 215 |
+
def constrain(self: _Pipeline[_InT, _OutT], constraint: _In) -> _Pipeline[_InT, _OutT]: ...
|
| 216 |
+
|
| 217 |
+
@overload
|
| 218 |
+
def constrain(self: _Pipeline[_InT, _OutT], constraint: _NotIn) -> _Pipeline[_InT, _OutT]: ...
|
| 219 |
+
|
| 220 |
+
@overload
|
| 221 |
+
def constrain(self: _Pipeline[_InT, _NewOutT], constraint: Pattern[str]) -> _Pipeline[_InT, _NewOutT]: ...
|
| 222 |
+
|
| 223 |
+
def constrain(self, constraint: _ConstraintAnnotation) -> Any:
|
| 224 |
+
"""Constrain a value to meet a certain condition.
|
| 225 |
+
|
| 226 |
+
We support most conditions from `annotated_types`, as well as regular expressions.
|
| 227 |
+
|
| 228 |
+
Most of the time you'll be calling a shortcut method like `gt`, `lt`, `len`, etc
|
| 229 |
+
so you don't need to call this directly.
|
| 230 |
+
"""
|
| 231 |
+
return _Pipeline[_InT, _OutT](self._steps + (_Constraint(constraint),))
|
| 232 |
+
|
| 233 |
+
def predicate(self: _Pipeline[_InT, _NewOutT], func: Callable[[_NewOutT], bool]) -> _Pipeline[_InT, _NewOutT]:
|
| 234 |
+
"""Constrain a value to meet a certain predicate."""
|
| 235 |
+
return self.constrain(annotated_types.Predicate(func))
|
| 236 |
+
|
| 237 |
+
def gt(self: _Pipeline[_InT, _NewOutGt], gt: _NewOutGt) -> _Pipeline[_InT, _NewOutGt]:
|
| 238 |
+
"""Constrain a value to be greater than a certain value."""
|
| 239 |
+
return self.constrain(annotated_types.Gt(gt))
|
| 240 |
+
|
| 241 |
+
def lt(self: _Pipeline[_InT, _NewOutLt], lt: _NewOutLt) -> _Pipeline[_InT, _NewOutLt]:
|
| 242 |
+
"""Constrain a value to be less than a certain value."""
|
| 243 |
+
return self.constrain(annotated_types.Lt(lt))
|
| 244 |
+
|
| 245 |
+
def ge(self: _Pipeline[_InT, _NewOutGe], ge: _NewOutGe) -> _Pipeline[_InT, _NewOutGe]:
|
| 246 |
+
"""Constrain a value to be greater than or equal to a certain value."""
|
| 247 |
+
return self.constrain(annotated_types.Ge(ge))
|
| 248 |
+
|
| 249 |
+
def le(self: _Pipeline[_InT, _NewOutLe], le: _NewOutLe) -> _Pipeline[_InT, _NewOutLe]:
|
| 250 |
+
"""Constrain a value to be less than or equal to a certain value."""
|
| 251 |
+
return self.constrain(annotated_types.Le(le))
|
| 252 |
+
|
| 253 |
+
def len(self: _Pipeline[_InT, _NewOutLen], min_len: int, max_len: int | None = None) -> _Pipeline[_InT, _NewOutLen]:
|
| 254 |
+
"""Constrain a value to have a certain length."""
|
| 255 |
+
return self.constrain(annotated_types.Len(min_len, max_len))
|
| 256 |
+
|
| 257 |
+
@overload
|
| 258 |
+
def multiple_of(self: _Pipeline[_InT, _NewOutDiv], multiple_of: _NewOutDiv) -> _Pipeline[_InT, _NewOutDiv]: ...
|
| 259 |
+
|
| 260 |
+
@overload
|
| 261 |
+
def multiple_of(self: _Pipeline[_InT, _NewOutMod], multiple_of: _NewOutMod) -> _Pipeline[_InT, _NewOutMod]: ...
|
| 262 |
+
|
| 263 |
+
def multiple_of(self: _Pipeline[_InT, Any], multiple_of: Any) -> _Pipeline[_InT, Any]:
|
| 264 |
+
"""Constrain a value to be a multiple of a certain number."""
|
| 265 |
+
return self.constrain(annotated_types.MultipleOf(multiple_of))
|
| 266 |
+
|
| 267 |
+
def eq(self: _Pipeline[_InT, _OutT], value: _OutT) -> _Pipeline[_InT, _OutT]:
|
| 268 |
+
"""Constrain a value to be equal to a certain value."""
|
| 269 |
+
return self.constrain(_Eq(value))
|
| 270 |
+
|
| 271 |
+
def not_eq(self: _Pipeline[_InT, _OutT], value: _OutT) -> _Pipeline[_InT, _OutT]:
|
| 272 |
+
"""Constrain a value to not be equal to a certain value."""
|
| 273 |
+
return self.constrain(_NotEq(value))
|
| 274 |
+
|
| 275 |
+
def in_(self: _Pipeline[_InT, _OutT], values: Container[_OutT]) -> _Pipeline[_InT, _OutT]:
|
| 276 |
+
"""Constrain a value to be in a certain set."""
|
| 277 |
+
return self.constrain(_In(values))
|
| 278 |
+
|
| 279 |
+
def not_in(self: _Pipeline[_InT, _OutT], values: Container[_OutT]) -> _Pipeline[_InT, _OutT]:
|
| 280 |
+
"""Constrain a value to not be in a certain set."""
|
| 281 |
+
return self.constrain(_NotIn(values))
|
| 282 |
+
|
| 283 |
+
# timezone methods
|
| 284 |
+
def datetime_tz_naive(self: _Pipeline[_InT, datetime.datetime]) -> _Pipeline[_InT, datetime.datetime]:
|
| 285 |
+
return self.constrain(annotated_types.Timezone(None))
|
| 286 |
+
|
| 287 |
+
def datetime_tz_aware(self: _Pipeline[_InT, datetime.datetime]) -> _Pipeline[_InT, datetime.datetime]:
|
| 288 |
+
return self.constrain(annotated_types.Timezone(...))
|
| 289 |
+
|
| 290 |
+
def datetime_tz(
|
| 291 |
+
self: _Pipeline[_InT, datetime.datetime], tz: datetime.tzinfo
|
| 292 |
+
) -> _Pipeline[_InT, datetime.datetime]:
|
| 293 |
+
return self.constrain(annotated_types.Timezone(tz)) # type: ignore
|
| 294 |
+
|
| 295 |
+
def datetime_with_tz(
|
| 296 |
+
self: _Pipeline[_InT, datetime.datetime], tz: datetime.tzinfo | None
|
| 297 |
+
) -> _Pipeline[_InT, datetime.datetime]:
|
| 298 |
+
return self.transform(partial(datetime.datetime.replace, tzinfo=tz))
|
| 299 |
+
|
| 300 |
+
# string methods
|
| 301 |
+
def str_lower(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]:
|
| 302 |
+
return self.transform(str.lower)
|
| 303 |
+
|
| 304 |
+
def str_upper(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]:
|
| 305 |
+
return self.transform(str.upper)
|
| 306 |
+
|
| 307 |
+
def str_title(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]:
|
| 308 |
+
return self.transform(str.title)
|
| 309 |
+
|
| 310 |
+
def str_strip(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]:
|
| 311 |
+
return self.transform(str.strip)
|
| 312 |
+
|
| 313 |
+
def str_pattern(self: _Pipeline[_InT, str], pattern: str) -> _Pipeline[_InT, str]:
|
| 314 |
+
return self.constrain(re.compile(pattern))
|
| 315 |
+
|
| 316 |
+
def str_contains(self: _Pipeline[_InT, str], substring: str) -> _Pipeline[_InT, str]:
|
| 317 |
+
return self.predicate(lambda v: substring in v)
|
| 318 |
+
|
| 319 |
+
def str_starts_with(self: _Pipeline[_InT, str], prefix: str) -> _Pipeline[_InT, str]:
|
| 320 |
+
return self.predicate(lambda v: v.startswith(prefix))
|
| 321 |
+
|
| 322 |
+
def str_ends_with(self: _Pipeline[_InT, str], suffix: str) -> _Pipeline[_InT, str]:
|
| 323 |
+
return self.predicate(lambda v: v.endswith(suffix))
|
| 324 |
+
|
| 325 |
+
# operators
|
| 326 |
+
def otherwise(self, other: _Pipeline[_OtherIn, _OtherOut]) -> _Pipeline[_InT | _OtherIn, _OutT | _OtherOut]:
|
| 327 |
+
"""Combine two validation chains, returning the result of the first chain if it succeeds, and the second chain if it fails."""
|
| 328 |
+
return _Pipeline((_PipelineOr(self, other),))
|
| 329 |
+
|
| 330 |
+
__or__ = otherwise
|
| 331 |
+
|
| 332 |
+
def then(self, other: _Pipeline[_OutT, _OtherOut]) -> _Pipeline[_InT, _OtherOut]:
|
| 333 |
+
"""Pipe the result of one validation chain into another."""
|
| 334 |
+
return _Pipeline((_PipelineAnd(self, other),))
|
| 335 |
+
|
| 336 |
+
__and__ = then
|
| 337 |
+
|
| 338 |
+
def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> cs.CoreSchema:
|
| 339 |
+
from pydantic_core import core_schema as cs
|
| 340 |
+
|
| 341 |
+
queue = deque(self._steps)
|
| 342 |
+
|
| 343 |
+
s = None
|
| 344 |
+
|
| 345 |
+
while queue:
|
| 346 |
+
step = queue.popleft()
|
| 347 |
+
s = _apply_step(step, s, handler, source_type)
|
| 348 |
+
|
| 349 |
+
s = s or cs.any_schema()
|
| 350 |
+
return s
|
| 351 |
+
|
| 352 |
+
def __supports_type__(self, _: _OutT) -> bool:
|
| 353 |
+
raise NotImplementedError
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
validate_as = _Pipeline[Any, Any](()).validate_as
|
| 357 |
+
validate_as_deferred = _Pipeline[Any, Any](()).validate_as_deferred
|
| 358 |
+
transform = _Pipeline[Any, Any]((_ValidateAs(_FieldTypeMarker),)).transform
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def _check_func(
|
| 362 |
+
func: Callable[[Any], bool], predicate_err: str | Callable[[], str], s: cs.CoreSchema | None
|
| 363 |
+
) -> cs.CoreSchema:
|
| 364 |
+
from pydantic_core import core_schema as cs
|
| 365 |
+
|
| 366 |
+
def handler(v: Any) -> Any:
|
| 367 |
+
if func(v):
|
| 368 |
+
return v
|
| 369 |
+
raise ValueError(f'Expected {predicate_err if isinstance(predicate_err, str) else predicate_err()}')
|
| 370 |
+
|
| 371 |
+
if s is None:
|
| 372 |
+
return cs.no_info_plain_validator_function(handler)
|
| 373 |
+
else:
|
| 374 |
+
return cs.no_info_after_validator_function(handler, s)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def _apply_step(step: _Step, s: cs.CoreSchema | None, handler: GetCoreSchemaHandler, source_type: Any) -> cs.CoreSchema:
|
| 378 |
+
from pydantic_core import core_schema as cs
|
| 379 |
+
|
| 380 |
+
if isinstance(step, _ValidateAs):
|
| 381 |
+
s = _apply_parse(s, step.tp, step.strict, handler, source_type)
|
| 382 |
+
elif isinstance(step, _ValidateAsDefer):
|
| 383 |
+
s = _apply_parse(s, step.tp, False, handler, source_type)
|
| 384 |
+
elif isinstance(step, _Transform):
|
| 385 |
+
s = _apply_transform(s, step.func, handler)
|
| 386 |
+
elif isinstance(step, _Constraint):
|
| 387 |
+
s = _apply_constraint(s, step.constraint)
|
| 388 |
+
elif isinstance(step, _PipelineOr):
|
| 389 |
+
s = cs.union_schema([handler(step.left), handler(step.right)])
|
| 390 |
+
else:
|
| 391 |
+
assert isinstance(step, _PipelineAnd)
|
| 392 |
+
s = cs.chain_schema([handler(step.left), handler(step.right)])
|
| 393 |
+
return s
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def _apply_parse(
|
| 397 |
+
s: cs.CoreSchema | None,
|
| 398 |
+
tp: type[Any],
|
| 399 |
+
strict: bool,
|
| 400 |
+
handler: GetCoreSchemaHandler,
|
| 401 |
+
source_type: Any,
|
| 402 |
+
) -> cs.CoreSchema:
|
| 403 |
+
from pydantic_core import core_schema as cs
|
| 404 |
+
|
| 405 |
+
from pydantic import Strict
|
| 406 |
+
|
| 407 |
+
if tp is _FieldTypeMarker:
|
| 408 |
+
return handler(source_type)
|
| 409 |
+
|
| 410 |
+
if strict:
|
| 411 |
+
tp = Annotated[tp, Strict()] # type: ignore
|
| 412 |
+
|
| 413 |
+
if s and s['type'] == 'any':
|
| 414 |
+
return handler(tp)
|
| 415 |
+
else:
|
| 416 |
+
return cs.chain_schema([s, handler(tp)]) if s else handler(tp)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def _apply_transform(
|
| 420 |
+
s: cs.CoreSchema | None, func: Callable[[Any], Any], handler: GetCoreSchemaHandler
|
| 421 |
+
) -> cs.CoreSchema:
|
| 422 |
+
from pydantic_core import core_schema as cs
|
| 423 |
+
|
| 424 |
+
if s is None:
|
| 425 |
+
return cs.no_info_plain_validator_function(func)
|
| 426 |
+
|
| 427 |
+
if s['type'] == 'str':
|
| 428 |
+
if func is str.strip:
|
| 429 |
+
s = s.copy()
|
| 430 |
+
s['strip_whitespace'] = True
|
| 431 |
+
return s
|
| 432 |
+
elif func is str.lower:
|
| 433 |
+
s = s.copy()
|
| 434 |
+
s['to_lower'] = True
|
| 435 |
+
return s
|
| 436 |
+
elif func is str.upper:
|
| 437 |
+
s = s.copy()
|
| 438 |
+
s['to_upper'] = True
|
| 439 |
+
return s
|
| 440 |
+
|
| 441 |
+
return cs.no_info_after_validator_function(func, s)
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
def _apply_constraint( # noqa: C901
|
| 445 |
+
s: cs.CoreSchema | None, constraint: _ConstraintAnnotation
|
| 446 |
+
) -> cs.CoreSchema:
|
| 447 |
+
"""Apply a single constraint to a schema."""
|
| 448 |
+
if isinstance(constraint, annotated_types.Gt):
|
| 449 |
+
gt = constraint.gt
|
| 450 |
+
if s and s['type'] in {'int', 'float', 'decimal'}:
|
| 451 |
+
s = s.copy()
|
| 452 |
+
if s['type'] == 'int' and isinstance(gt, int):
|
| 453 |
+
s['gt'] = gt
|
| 454 |
+
elif s['type'] == 'float' and isinstance(gt, float):
|
| 455 |
+
s['gt'] = gt
|
| 456 |
+
elif s['type'] == 'decimal' and isinstance(gt, Decimal):
|
| 457 |
+
s['gt'] = gt
|
| 458 |
+
else:
|
| 459 |
+
|
| 460 |
+
def check_gt(v: Any) -> bool:
|
| 461 |
+
return v > gt
|
| 462 |
+
|
| 463 |
+
s = _check_func(check_gt, f'> {gt}', s)
|
| 464 |
+
elif isinstance(constraint, annotated_types.Ge):
|
| 465 |
+
ge = constraint.ge
|
| 466 |
+
if s and s['type'] in {'int', 'float', 'decimal'}:
|
| 467 |
+
s = s.copy()
|
| 468 |
+
if s['type'] == 'int' and isinstance(ge, int):
|
| 469 |
+
s['ge'] = ge
|
| 470 |
+
elif s['type'] == 'float' and isinstance(ge, float):
|
| 471 |
+
s['ge'] = ge
|
| 472 |
+
elif s['type'] == 'decimal' and isinstance(ge, Decimal):
|
| 473 |
+
s['ge'] = ge
|
| 474 |
+
|
| 475 |
+
def check_ge(v: Any) -> bool:
|
| 476 |
+
return v >= ge
|
| 477 |
+
|
| 478 |
+
s = _check_func(check_ge, f'>= {ge}', s)
|
| 479 |
+
elif isinstance(constraint, annotated_types.Lt):
|
| 480 |
+
lt = constraint.lt
|
| 481 |
+
if s and s['type'] in {'int', 'float', 'decimal'}:
|
| 482 |
+
s = s.copy()
|
| 483 |
+
if s['type'] == 'int' and isinstance(lt, int):
|
| 484 |
+
s['lt'] = lt
|
| 485 |
+
elif s['type'] == 'float' and isinstance(lt, float):
|
| 486 |
+
s['lt'] = lt
|
| 487 |
+
elif s['type'] == 'decimal' and isinstance(lt, Decimal):
|
| 488 |
+
s['lt'] = lt
|
| 489 |
+
|
| 490 |
+
def check_lt(v: Any) -> bool:
|
| 491 |
+
return v < lt
|
| 492 |
+
|
| 493 |
+
s = _check_func(check_lt, f'< {lt}', s)
|
| 494 |
+
elif isinstance(constraint, annotated_types.Le):
|
| 495 |
+
le = constraint.le
|
| 496 |
+
if s and s['type'] in {'int', 'float', 'decimal'}:
|
| 497 |
+
s = s.copy()
|
| 498 |
+
if s['type'] == 'int' and isinstance(le, int):
|
| 499 |
+
s['le'] = le
|
| 500 |
+
elif s['type'] == 'float' and isinstance(le, float):
|
| 501 |
+
s['le'] = le
|
| 502 |
+
elif s['type'] == 'decimal' and isinstance(le, Decimal):
|
| 503 |
+
s['le'] = le
|
| 504 |
+
|
| 505 |
+
def check_le(v: Any) -> bool:
|
| 506 |
+
return v <= le
|
| 507 |
+
|
| 508 |
+
s = _check_func(check_le, f'<= {le}', s)
|
| 509 |
+
elif isinstance(constraint, annotated_types.Len):
|
| 510 |
+
min_len = constraint.min_length
|
| 511 |
+
max_len = constraint.max_length
|
| 512 |
+
|
| 513 |
+
if s and s['type'] in {'str', 'list', 'tuple', 'set', 'frozenset', 'dict'}:
|
| 514 |
+
assert (
|
| 515 |
+
s['type'] == 'str'
|
| 516 |
+
or s['type'] == 'list'
|
| 517 |
+
or s['type'] == 'tuple'
|
| 518 |
+
or s['type'] == 'set'
|
| 519 |
+
or s['type'] == 'dict'
|
| 520 |
+
or s['type'] == 'frozenset'
|
| 521 |
+
)
|
| 522 |
+
s = s.copy()
|
| 523 |
+
if min_len != 0:
|
| 524 |
+
s['min_length'] = min_len
|
| 525 |
+
if max_len is not None:
|
| 526 |
+
s['max_length'] = max_len
|
| 527 |
+
|
| 528 |
+
def check_len(v: Any) -> bool:
|
| 529 |
+
if max_len is not None:
|
| 530 |
+
return (min_len <= len(v)) and (len(v) <= max_len)
|
| 531 |
+
return min_len <= len(v)
|
| 532 |
+
|
| 533 |
+
s = _check_func(check_len, f'length >= {min_len} and length <= {max_len}', s)
|
| 534 |
+
elif isinstance(constraint, annotated_types.MultipleOf):
|
| 535 |
+
multiple_of = constraint.multiple_of
|
| 536 |
+
if s and s['type'] in {'int', 'float', 'decimal'}:
|
| 537 |
+
s = s.copy()
|
| 538 |
+
if s['type'] == 'int' and isinstance(multiple_of, int):
|
| 539 |
+
s['multiple_of'] = multiple_of
|
| 540 |
+
elif s['type'] == 'float' and isinstance(multiple_of, float):
|
| 541 |
+
s['multiple_of'] = multiple_of
|
| 542 |
+
elif s['type'] == 'decimal' and isinstance(multiple_of, Decimal):
|
| 543 |
+
s['multiple_of'] = multiple_of
|
| 544 |
+
|
| 545 |
+
def check_multiple_of(v: Any) -> bool:
|
| 546 |
+
return v % multiple_of == 0
|
| 547 |
+
|
| 548 |
+
s = _check_func(check_multiple_of, f'% {multiple_of} == 0', s)
|
| 549 |
+
elif isinstance(constraint, annotated_types.Timezone):
|
| 550 |
+
tz = constraint.tz
|
| 551 |
+
|
| 552 |
+
if tz is ...:
|
| 553 |
+
if s and s['type'] == 'datetime':
|
| 554 |
+
s = s.copy()
|
| 555 |
+
s['tz_constraint'] = 'aware'
|
| 556 |
+
else:
|
| 557 |
+
|
| 558 |
+
def check_tz_aware(v: object) -> bool:
|
| 559 |
+
assert isinstance(v, datetime.datetime)
|
| 560 |
+
return v.tzinfo is not None
|
| 561 |
+
|
| 562 |
+
s = _check_func(check_tz_aware, 'timezone aware', s)
|
| 563 |
+
elif tz is None:
|
| 564 |
+
if s and s['type'] == 'datetime':
|
| 565 |
+
s = s.copy()
|
| 566 |
+
s['tz_constraint'] = 'naive'
|
| 567 |
+
else:
|
| 568 |
+
|
| 569 |
+
def check_tz_naive(v: object) -> bool:
|
| 570 |
+
assert isinstance(v, datetime.datetime)
|
| 571 |
+
return v.tzinfo is None
|
| 572 |
+
|
| 573 |
+
s = _check_func(check_tz_naive, 'timezone naive', s)
|
| 574 |
+
else:
|
| 575 |
+
raise NotImplementedError('Constraining to a specific timezone is not yet supported')
|
| 576 |
+
elif isinstance(constraint, annotated_types.Interval):
|
| 577 |
+
if constraint.ge:
|
| 578 |
+
s = _apply_constraint(s, annotated_types.Ge(constraint.ge))
|
| 579 |
+
if constraint.gt:
|
| 580 |
+
s = _apply_constraint(s, annotated_types.Gt(constraint.gt))
|
| 581 |
+
if constraint.le:
|
| 582 |
+
s = _apply_constraint(s, annotated_types.Le(constraint.le))
|
| 583 |
+
if constraint.lt:
|
| 584 |
+
s = _apply_constraint(s, annotated_types.Lt(constraint.lt))
|
| 585 |
+
assert s is not None
|
| 586 |
+
elif isinstance(constraint, annotated_types.Predicate):
|
| 587 |
+
func = constraint.func
|
| 588 |
+
|
| 589 |
+
if func.__name__ == '<lambda>':
|
| 590 |
+
# attempt to extract the source code for a lambda function
|
| 591 |
+
# to use as the function name in error messages
|
| 592 |
+
# TODO: is there a better way? should we just not do this?
|
| 593 |
+
import inspect
|
| 594 |
+
|
| 595 |
+
try:
|
| 596 |
+
# remove ')' suffix, can use removesuffix once we drop 3.8
|
| 597 |
+
source = inspect.getsource(func).strip()
|
| 598 |
+
if source.endswith(')'):
|
| 599 |
+
source = source[:-1]
|
| 600 |
+
lambda_source_code = '`' + ''.join(''.join(source.split('lambda ')[1:]).split(':')[1:]).strip() + '`'
|
| 601 |
+
except OSError:
|
| 602 |
+
# stringified annotations
|
| 603 |
+
lambda_source_code = 'lambda'
|
| 604 |
+
|
| 605 |
+
s = _check_func(func, lambda_source_code, s)
|
| 606 |
+
else:
|
| 607 |
+
s = _check_func(func, func.__name__, s)
|
| 608 |
+
elif isinstance(constraint, _NotEq):
|
| 609 |
+
value = constraint.value
|
| 610 |
+
|
| 611 |
+
def check_not_eq(v: Any) -> bool:
|
| 612 |
+
return operator.__ne__(v, value)
|
| 613 |
+
|
| 614 |
+
s = _check_func(check_not_eq, f'!= {value}', s)
|
| 615 |
+
elif isinstance(constraint, _Eq):
|
| 616 |
+
value = constraint.value
|
| 617 |
+
|
| 618 |
+
def check_eq(v: Any) -> bool:
|
| 619 |
+
return operator.__eq__(v, value)
|
| 620 |
+
|
| 621 |
+
s = _check_func(check_eq, f'== {value}', s)
|
| 622 |
+
elif isinstance(constraint, _In):
|
| 623 |
+
values = constraint.values
|
| 624 |
+
|
| 625 |
+
def check_in(v: Any) -> bool:
|
| 626 |
+
return operator.__contains__(values, v)
|
| 627 |
+
|
| 628 |
+
s = _check_func(check_in, f'in {values}', s)
|
| 629 |
+
elif isinstance(constraint, _NotIn):
|
| 630 |
+
values = constraint.values
|
| 631 |
+
|
| 632 |
+
def check_not_in(v: Any) -> bool:
|
| 633 |
+
return operator.__not__(operator.__contains__(values, v))
|
| 634 |
+
|
| 635 |
+
s = _check_func(check_not_in, f'not in {values}', s)
|
| 636 |
+
else:
|
| 637 |
+
assert isinstance(constraint, Pattern)
|
| 638 |
+
if s and s['type'] == 'str':
|
| 639 |
+
s = s.copy()
|
| 640 |
+
s['pattern'] = constraint.pattern
|
| 641 |
+
else:
|
| 642 |
+
|
| 643 |
+
def check_pattern(v: object) -> bool:
|
| 644 |
+
assert isinstance(v, str)
|
| 645 |
+
return constraint.match(v) is not None
|
| 646 |
+
|
| 647 |
+
s = _check_func(check_pattern, f'~ {constraint.pattern}', s)
|
| 648 |
+
return s
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
class _SupportsRange(annotated_types.SupportsLe, annotated_types.SupportsGe, Protocol):
|
| 652 |
+
pass
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
class _SupportsLen(Protocol):
|
| 656 |
+
def __len__(self) -> int: ...
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
_NewOutGt = TypeVar('_NewOutGt', bound=annotated_types.SupportsGt)
|
| 660 |
+
_NewOutGe = TypeVar('_NewOutGe', bound=annotated_types.SupportsGe)
|
| 661 |
+
_NewOutLt = TypeVar('_NewOutLt', bound=annotated_types.SupportsLt)
|
| 662 |
+
_NewOutLe = TypeVar('_NewOutLe', bound=annotated_types.SupportsLe)
|
| 663 |
+
_NewOutLen = TypeVar('_NewOutLen', bound=_SupportsLen)
|
| 664 |
+
_NewOutDiv = TypeVar('_NewOutDiv', bound=annotated_types.SupportsDiv)
|
| 665 |
+
_NewOutMod = TypeVar('_NewOutMod', bound=annotated_types.SupportsMod)
|
| 666 |
+
_NewOutDatetime = TypeVar('_NewOutDatetime', bound=datetime.datetime)
|
| 667 |
+
_NewOutInterval = TypeVar('_NewOutInterval', bound=_SupportsRange)
|
| 668 |
+
_OtherIn = TypeVar('_OtherIn')
|
| 669 |
+
_OtherOut = TypeVar('_OtherOut')
|
vllm/lib/python3.10/site-packages/pydantic/fields.py
ADDED
|
@@ -0,0 +1,1504 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Defining fields on models."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations as _annotations
|
| 4 |
+
|
| 5 |
+
import dataclasses
|
| 6 |
+
import inspect
|
| 7 |
+
import sys
|
| 8 |
+
import typing
|
| 9 |
+
from copy import copy
|
| 10 |
+
from dataclasses import Field as DataclassField
|
| 11 |
+
from functools import cached_property
|
| 12 |
+
from typing import Any, Callable, ClassVar, TypeVar, cast, overload
|
| 13 |
+
from warnings import warn
|
| 14 |
+
|
| 15 |
+
import annotated_types
|
| 16 |
+
import typing_extensions
|
| 17 |
+
from pydantic_core import PydanticUndefined
|
| 18 |
+
from typing_extensions import Literal, TypeAlias, Unpack, deprecated
|
| 19 |
+
|
| 20 |
+
from . import types
|
| 21 |
+
from ._internal import _decorators, _fields, _generics, _internal_dataclass, _repr, _typing_extra, _utils
|
| 22 |
+
from ._internal._namespace_utils import GlobalsNamespace, MappingNamespace
|
| 23 |
+
from .aliases import AliasChoices, AliasPath
|
| 24 |
+
from .config import JsonDict
|
| 25 |
+
from .errors import PydanticUserError
|
| 26 |
+
from .json_schema import PydanticJsonSchemaWarning
|
| 27 |
+
from .warnings import PydanticDeprecatedSince20
|
| 28 |
+
|
| 29 |
+
if typing.TYPE_CHECKING:
|
| 30 |
+
from ._internal._repr import ReprArgs
|
| 31 |
+
else:
|
| 32 |
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
| 33 |
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
| 34 |
+
DeprecationWarning = PydanticDeprecatedSince20
|
| 35 |
+
|
| 36 |
+
__all__ = 'Field', 'PrivateAttr', 'computed_field'
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
_Unset: Any = PydanticUndefined
|
| 40 |
+
|
| 41 |
+
if sys.version_info >= (3, 13):
|
| 42 |
+
import warnings
|
| 43 |
+
|
| 44 |
+
Deprecated: TypeAlias = warnings.deprecated | deprecated
|
| 45 |
+
else:
|
| 46 |
+
Deprecated: TypeAlias = deprecated
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class _FromFieldInfoInputs(typing_extensions.TypedDict, total=False):
|
| 50 |
+
"""This class exists solely to add type checking for the `**kwargs` in `FieldInfo.from_field`."""
|
| 51 |
+
|
| 52 |
+
annotation: type[Any] | None
|
| 53 |
+
default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None
|
| 54 |
+
alias: str | None
|
| 55 |
+
alias_priority: int | None
|
| 56 |
+
validation_alias: str | AliasPath | AliasChoices | None
|
| 57 |
+
serialization_alias: str | None
|
| 58 |
+
title: str | None
|
| 59 |
+
field_title_generator: Callable[[str, FieldInfo], str] | None
|
| 60 |
+
description: str | None
|
| 61 |
+
examples: list[Any] | None
|
| 62 |
+
exclude: bool | None
|
| 63 |
+
gt: annotated_types.SupportsGt | None
|
| 64 |
+
ge: annotated_types.SupportsGe | None
|
| 65 |
+
lt: annotated_types.SupportsLt | None
|
| 66 |
+
le: annotated_types.SupportsLe | None
|
| 67 |
+
multiple_of: float | None
|
| 68 |
+
strict: bool | None
|
| 69 |
+
min_length: int | None
|
| 70 |
+
max_length: int | None
|
| 71 |
+
pattern: str | typing.Pattern[str] | None
|
| 72 |
+
allow_inf_nan: bool | None
|
| 73 |
+
max_digits: int | None
|
| 74 |
+
decimal_places: int | None
|
| 75 |
+
union_mode: Literal['smart', 'left_to_right'] | None
|
| 76 |
+
discriminator: str | types.Discriminator | None
|
| 77 |
+
deprecated: Deprecated | str | bool | None
|
| 78 |
+
json_schema_extra: JsonDict | Callable[[JsonDict], None] | None
|
| 79 |
+
frozen: bool | None
|
| 80 |
+
validate_default: bool | None
|
| 81 |
+
repr: bool
|
| 82 |
+
init: bool | None
|
| 83 |
+
init_var: bool | None
|
| 84 |
+
kw_only: bool | None
|
| 85 |
+
coerce_numbers_to_str: bool | None
|
| 86 |
+
fail_fast: bool | None
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class _FieldInfoInputs(_FromFieldInfoInputs, total=False):
|
| 90 |
+
"""This class exists solely to add type checking for the `**kwargs` in `FieldInfo.__init__`."""
|
| 91 |
+
|
| 92 |
+
default: Any
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class FieldInfo(_repr.Representation):
|
| 96 |
+
"""This class holds information about a field.
|
| 97 |
+
|
| 98 |
+
`FieldInfo` is used for any field definition regardless of whether the [`Field()`][pydantic.fields.Field]
|
| 99 |
+
function is explicitly used.
|
| 100 |
+
|
| 101 |
+
!!! warning
|
| 102 |
+
You generally shouldn't be creating `FieldInfo` directly, you'll only need to use it when accessing
|
| 103 |
+
[`BaseModel`][pydantic.main.BaseModel] `.model_fields` internals.
|
| 104 |
+
|
| 105 |
+
Attributes:
|
| 106 |
+
annotation: The type annotation of the field.
|
| 107 |
+
default: The default value of the field.
|
| 108 |
+
default_factory: A callable to generate the default value. The callable can either take 0 arguments
|
| 109 |
+
(in which case it is called as is) or a single argument containing the already validated data.
|
| 110 |
+
alias: The alias name of the field.
|
| 111 |
+
alias_priority: The priority of the field's alias.
|
| 112 |
+
validation_alias: The validation alias of the field.
|
| 113 |
+
serialization_alias: The serialization alias of the field.
|
| 114 |
+
title: The title of the field.
|
| 115 |
+
field_title_generator: A callable that takes a field name and returns title for it.
|
| 116 |
+
description: The description of the field.
|
| 117 |
+
examples: List of examples of the field.
|
| 118 |
+
exclude: Whether to exclude the field from the model serialization.
|
| 119 |
+
discriminator: Field name or Discriminator for discriminating the type in a tagged union.
|
| 120 |
+
deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
|
| 121 |
+
or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
|
| 122 |
+
json_schema_extra: A dict or callable to provide extra JSON schema properties.
|
| 123 |
+
frozen: Whether the field is frozen.
|
| 124 |
+
validate_default: Whether to validate the default value of the field.
|
| 125 |
+
repr: Whether to include the field in representation of the model.
|
| 126 |
+
init: Whether the field should be included in the constructor of the dataclass.
|
| 127 |
+
init_var: Whether the field should _only_ be included in the constructor of the dataclass, and not stored.
|
| 128 |
+
kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass.
|
| 129 |
+
metadata: List of metadata constraints.
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
annotation: type[Any] | None
|
| 133 |
+
default: Any
|
| 134 |
+
default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None
|
| 135 |
+
alias: str | None
|
| 136 |
+
alias_priority: int | None
|
| 137 |
+
validation_alias: str | AliasPath | AliasChoices | None
|
| 138 |
+
serialization_alias: str | None
|
| 139 |
+
title: str | None
|
| 140 |
+
field_title_generator: Callable[[str, FieldInfo], str] | None
|
| 141 |
+
description: str | None
|
| 142 |
+
examples: list[Any] | None
|
| 143 |
+
exclude: bool | None
|
| 144 |
+
discriminator: str | types.Discriminator | None
|
| 145 |
+
deprecated: Deprecated | str | bool | None
|
| 146 |
+
json_schema_extra: JsonDict | Callable[[JsonDict], None] | None
|
| 147 |
+
frozen: bool | None
|
| 148 |
+
validate_default: bool | None
|
| 149 |
+
repr: bool
|
| 150 |
+
init: bool | None
|
| 151 |
+
init_var: bool | None
|
| 152 |
+
kw_only: bool | None
|
| 153 |
+
metadata: list[Any]
|
| 154 |
+
|
| 155 |
+
__slots__ = (
|
| 156 |
+
'annotation',
|
| 157 |
+
'evaluated',
|
| 158 |
+
'default',
|
| 159 |
+
'default_factory',
|
| 160 |
+
'alias',
|
| 161 |
+
'alias_priority',
|
| 162 |
+
'validation_alias',
|
| 163 |
+
'serialization_alias',
|
| 164 |
+
'title',
|
| 165 |
+
'field_title_generator',
|
| 166 |
+
'description',
|
| 167 |
+
'examples',
|
| 168 |
+
'exclude',
|
| 169 |
+
'discriminator',
|
| 170 |
+
'deprecated',
|
| 171 |
+
'json_schema_extra',
|
| 172 |
+
'frozen',
|
| 173 |
+
'validate_default',
|
| 174 |
+
'repr',
|
| 175 |
+
'init',
|
| 176 |
+
'init_var',
|
| 177 |
+
'kw_only',
|
| 178 |
+
'metadata',
|
| 179 |
+
'_attributes_set',
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
# used to convert kwargs to metadata/constraints,
|
| 183 |
+
# None has a special meaning - these items are collected into a `PydanticGeneralMetadata`
|
| 184 |
+
metadata_lookup: ClassVar[dict[str, typing.Callable[[Any], Any] | None]] = {
|
| 185 |
+
'strict': types.Strict,
|
| 186 |
+
'gt': annotated_types.Gt,
|
| 187 |
+
'ge': annotated_types.Ge,
|
| 188 |
+
'lt': annotated_types.Lt,
|
| 189 |
+
'le': annotated_types.Le,
|
| 190 |
+
'multiple_of': annotated_types.MultipleOf,
|
| 191 |
+
'min_length': annotated_types.MinLen,
|
| 192 |
+
'max_length': annotated_types.MaxLen,
|
| 193 |
+
'pattern': None,
|
| 194 |
+
'allow_inf_nan': None,
|
| 195 |
+
'max_digits': None,
|
| 196 |
+
'decimal_places': None,
|
| 197 |
+
'union_mode': None,
|
| 198 |
+
'coerce_numbers_to_str': None,
|
| 199 |
+
'fail_fast': types.FailFast,
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
def __init__(self, **kwargs: Unpack[_FieldInfoInputs]) -> None:
|
| 203 |
+
"""This class should generally not be initialized directly; instead, use the `pydantic.fields.Field` function
|
| 204 |
+
or one of the constructor classmethods.
|
| 205 |
+
|
| 206 |
+
See the signature of `pydantic.fields.Field` for more details about the expected arguments.
|
| 207 |
+
"""
|
| 208 |
+
self._attributes_set = {k: v for k, v in kwargs.items() if v is not _Unset}
|
| 209 |
+
kwargs = {k: _DefaultValues.get(k) if v is _Unset else v for k, v in kwargs.items()} # type: ignore
|
| 210 |
+
self.annotation, annotation_metadata = self._extract_metadata(kwargs.get('annotation'))
|
| 211 |
+
self.evaluated = False
|
| 212 |
+
|
| 213 |
+
default = kwargs.pop('default', PydanticUndefined)
|
| 214 |
+
if default is Ellipsis:
|
| 215 |
+
self.default = PydanticUndefined
|
| 216 |
+
# Also remove it from the attributes set, otherwise
|
| 217 |
+
# `GenerateSchema._common_field_schema` mistakenly
|
| 218 |
+
# uses it:
|
| 219 |
+
self._attributes_set.pop('default', None)
|
| 220 |
+
else:
|
| 221 |
+
self.default = default
|
| 222 |
+
|
| 223 |
+
self.default_factory = kwargs.pop('default_factory', None)
|
| 224 |
+
|
| 225 |
+
if self.default is not PydanticUndefined and self.default_factory is not None:
|
| 226 |
+
raise TypeError('cannot specify both default and default_factory')
|
| 227 |
+
|
| 228 |
+
self.alias = kwargs.pop('alias', None)
|
| 229 |
+
self.validation_alias = kwargs.pop('validation_alias', None)
|
| 230 |
+
self.serialization_alias = kwargs.pop('serialization_alias', None)
|
| 231 |
+
alias_is_set = any(alias is not None for alias in (self.alias, self.validation_alias, self.serialization_alias))
|
| 232 |
+
self.alias_priority = kwargs.pop('alias_priority', None) or 2 if alias_is_set else None
|
| 233 |
+
self.title = kwargs.pop('title', None)
|
| 234 |
+
self.field_title_generator = kwargs.pop('field_title_generator', None)
|
| 235 |
+
self.description = kwargs.pop('description', None)
|
| 236 |
+
self.examples = kwargs.pop('examples', None)
|
| 237 |
+
self.exclude = kwargs.pop('exclude', None)
|
| 238 |
+
self.discriminator = kwargs.pop('discriminator', None)
|
| 239 |
+
# For compatibility with FastAPI<=0.110.0, we preserve the existing value if it is not overridden
|
| 240 |
+
self.deprecated = kwargs.pop('deprecated', getattr(self, 'deprecated', None))
|
| 241 |
+
self.repr = kwargs.pop('repr', True)
|
| 242 |
+
self.json_schema_extra = kwargs.pop('json_schema_extra', None)
|
| 243 |
+
self.validate_default = kwargs.pop('validate_default', None)
|
| 244 |
+
self.frozen = kwargs.pop('frozen', None)
|
| 245 |
+
# currently only used on dataclasses
|
| 246 |
+
self.init = kwargs.pop('init', None)
|
| 247 |
+
self.init_var = kwargs.pop('init_var', None)
|
| 248 |
+
self.kw_only = kwargs.pop('kw_only', None)
|
| 249 |
+
|
| 250 |
+
self.metadata = self._collect_metadata(kwargs) + annotation_metadata # type: ignore
|
| 251 |
+
|
| 252 |
+
@staticmethod
|
| 253 |
+
def from_field(default: Any = PydanticUndefined, **kwargs: Unpack[_FromFieldInfoInputs]) -> FieldInfo:
|
| 254 |
+
"""Create a new `FieldInfo` object with the `Field` function.
|
| 255 |
+
|
| 256 |
+
Args:
|
| 257 |
+
default: The default value for the field. Defaults to Undefined.
|
| 258 |
+
**kwargs: Additional arguments dictionary.
|
| 259 |
+
|
| 260 |
+
Raises:
|
| 261 |
+
TypeError: If 'annotation' is passed as a keyword argument.
|
| 262 |
+
|
| 263 |
+
Returns:
|
| 264 |
+
A new FieldInfo object with the given parameters.
|
| 265 |
+
|
| 266 |
+
Example:
|
| 267 |
+
This is how you can create a field with default value like this:
|
| 268 |
+
|
| 269 |
+
```python
|
| 270 |
+
import pydantic
|
| 271 |
+
|
| 272 |
+
class MyModel(pydantic.BaseModel):
|
| 273 |
+
foo: int = pydantic.Field(4)
|
| 274 |
+
```
|
| 275 |
+
"""
|
| 276 |
+
if 'annotation' in kwargs:
|
| 277 |
+
raise TypeError('"annotation" is not permitted as a Field keyword argument')
|
| 278 |
+
return FieldInfo(default=default, **kwargs)
|
| 279 |
+
|
| 280 |
+
@staticmethod
|
| 281 |
+
def from_annotation(annotation: type[Any]) -> FieldInfo:
|
| 282 |
+
"""Creates a `FieldInfo` instance from a bare annotation.
|
| 283 |
+
|
| 284 |
+
This function is used internally to create a `FieldInfo` from a bare annotation like this:
|
| 285 |
+
|
| 286 |
+
```python
|
| 287 |
+
import pydantic
|
| 288 |
+
|
| 289 |
+
class MyModel(pydantic.BaseModel):
|
| 290 |
+
foo: int # <-- like this
|
| 291 |
+
```
|
| 292 |
+
|
| 293 |
+
We also account for the case where the annotation can be an instance of `Annotated` and where
|
| 294 |
+
one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.:
|
| 295 |
+
|
| 296 |
+
```python
|
| 297 |
+
import annotated_types
|
| 298 |
+
from typing_extensions import Annotated
|
| 299 |
+
|
| 300 |
+
import pydantic
|
| 301 |
+
|
| 302 |
+
class MyModel(pydantic.BaseModel):
|
| 303 |
+
foo: Annotated[int, annotated_types.Gt(42)]
|
| 304 |
+
bar: Annotated[int, pydantic.Field(gt=42)]
|
| 305 |
+
```
|
| 306 |
+
|
| 307 |
+
Args:
|
| 308 |
+
annotation: An annotation object.
|
| 309 |
+
|
| 310 |
+
Returns:
|
| 311 |
+
An instance of the field metadata.
|
| 312 |
+
"""
|
| 313 |
+
final = False
|
| 314 |
+
if _typing_extra.is_finalvar(annotation):
|
| 315 |
+
final = True
|
| 316 |
+
if annotation is not typing_extensions.Final:
|
| 317 |
+
annotation = typing_extensions.get_args(annotation)[0]
|
| 318 |
+
|
| 319 |
+
if _typing_extra.is_annotated(annotation):
|
| 320 |
+
first_arg, *extra_args = typing_extensions.get_args(annotation)
|
| 321 |
+
if _typing_extra.is_finalvar(first_arg):
|
| 322 |
+
final = True
|
| 323 |
+
field_info_annotations = [a for a in extra_args if isinstance(a, FieldInfo)]
|
| 324 |
+
field_info = FieldInfo.merge_field_infos(*field_info_annotations, annotation=first_arg)
|
| 325 |
+
if field_info:
|
| 326 |
+
new_field_info = copy(field_info)
|
| 327 |
+
new_field_info.annotation = first_arg
|
| 328 |
+
new_field_info.frozen = final or field_info.frozen
|
| 329 |
+
metadata: list[Any] = []
|
| 330 |
+
for a in extra_args:
|
| 331 |
+
if _typing_extra.is_deprecated_instance(a):
|
| 332 |
+
new_field_info.deprecated = a.message
|
| 333 |
+
elif not isinstance(a, FieldInfo):
|
| 334 |
+
metadata.append(a)
|
| 335 |
+
else:
|
| 336 |
+
metadata.extend(a.metadata)
|
| 337 |
+
new_field_info.metadata = metadata
|
| 338 |
+
return new_field_info
|
| 339 |
+
|
| 340 |
+
return FieldInfo(annotation=annotation, frozen=final or None) # pyright: ignore[reportArgumentType]
|
| 341 |
+
|
| 342 |
+
@staticmethod
|
| 343 |
+
def from_annotated_attribute(annotation: type[Any], default: Any) -> FieldInfo:
|
| 344 |
+
"""Create `FieldInfo` from an annotation with a default value.
|
| 345 |
+
|
| 346 |
+
This is used in cases like the following:
|
| 347 |
+
|
| 348 |
+
```python
|
| 349 |
+
import annotated_types
|
| 350 |
+
from typing_extensions import Annotated
|
| 351 |
+
|
| 352 |
+
import pydantic
|
| 353 |
+
|
| 354 |
+
class MyModel(pydantic.BaseModel):
|
| 355 |
+
foo: int = 4 # <-- like this
|
| 356 |
+
bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this
|
| 357 |
+
spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this
|
| 358 |
+
```
|
| 359 |
+
|
| 360 |
+
Args:
|
| 361 |
+
annotation: The type annotation of the field.
|
| 362 |
+
default: The default value of the field.
|
| 363 |
+
|
| 364 |
+
Returns:
|
| 365 |
+
A field object with the passed values.
|
| 366 |
+
"""
|
| 367 |
+
if annotation is default:
|
| 368 |
+
raise PydanticUserError(
|
| 369 |
+
'Error when building FieldInfo from annotated attribute. '
|
| 370 |
+
"Make sure you don't have any field name clashing with a type annotation ",
|
| 371 |
+
code='unevaluable-type-annotation',
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
final = _typing_extra.is_finalvar(annotation)
|
| 375 |
+
if final and annotation is not typing_extensions.Final:
|
| 376 |
+
annotation = typing_extensions.get_args(annotation)[0]
|
| 377 |
+
|
| 378 |
+
if isinstance(default, FieldInfo):
|
| 379 |
+
default.annotation, annotation_metadata = FieldInfo._extract_metadata(annotation) # pyright: ignore[reportArgumentType]
|
| 380 |
+
default.metadata += annotation_metadata
|
| 381 |
+
default = default.merge_field_infos(
|
| 382 |
+
*[x for x in annotation_metadata if isinstance(x, FieldInfo)], default, annotation=default.annotation
|
| 383 |
+
)
|
| 384 |
+
default.frozen = final or default.frozen
|
| 385 |
+
return default
|
| 386 |
+
|
| 387 |
+
if isinstance(default, dataclasses.Field):
|
| 388 |
+
init_var = False
|
| 389 |
+
if annotation is dataclasses.InitVar:
|
| 390 |
+
init_var = True
|
| 391 |
+
annotation = typing.cast(Any, Any)
|
| 392 |
+
elif isinstance(annotation, dataclasses.InitVar):
|
| 393 |
+
init_var = True
|
| 394 |
+
annotation = annotation.type
|
| 395 |
+
|
| 396 |
+
pydantic_field = FieldInfo._from_dataclass_field(default)
|
| 397 |
+
pydantic_field.annotation, annotation_metadata = FieldInfo._extract_metadata(annotation) # pyright: ignore[reportArgumentType]
|
| 398 |
+
pydantic_field.metadata += annotation_metadata
|
| 399 |
+
pydantic_field = pydantic_field.merge_field_infos(
|
| 400 |
+
*[x for x in annotation_metadata if isinstance(x, FieldInfo)],
|
| 401 |
+
pydantic_field,
|
| 402 |
+
annotation=pydantic_field.annotation,
|
| 403 |
+
)
|
| 404 |
+
pydantic_field.frozen = final or pydantic_field.frozen
|
| 405 |
+
pydantic_field.init_var = init_var
|
| 406 |
+
pydantic_field.init = getattr(default, 'init', None)
|
| 407 |
+
pydantic_field.kw_only = getattr(default, 'kw_only', None)
|
| 408 |
+
return pydantic_field
|
| 409 |
+
|
| 410 |
+
if _typing_extra.is_annotated(annotation):
|
| 411 |
+
first_arg, *extra_args = typing_extensions.get_args(annotation)
|
| 412 |
+
field_infos = [a for a in extra_args if isinstance(a, FieldInfo)]
|
| 413 |
+
field_info = FieldInfo.merge_field_infos(*field_infos, annotation=first_arg, default=default)
|
| 414 |
+
metadata: list[Any] = []
|
| 415 |
+
for a in extra_args:
|
| 416 |
+
if _typing_extra.is_deprecated_instance(a):
|
| 417 |
+
field_info.deprecated = a.message
|
| 418 |
+
elif not isinstance(a, FieldInfo):
|
| 419 |
+
metadata.append(a)
|
| 420 |
+
else:
|
| 421 |
+
metadata.extend(a.metadata)
|
| 422 |
+
field_info.metadata = metadata
|
| 423 |
+
return field_info
|
| 424 |
+
|
| 425 |
+
return FieldInfo(annotation=annotation, default=default, frozen=final or None) # pyright: ignore[reportArgumentType]
|
| 426 |
+
|
| 427 |
+
@staticmethod
|
| 428 |
+
def merge_field_infos(*field_infos: FieldInfo, **overrides: Any) -> FieldInfo:
|
| 429 |
+
"""Merge `FieldInfo` instances keeping only explicitly set attributes.
|
| 430 |
+
|
| 431 |
+
Later `FieldInfo` instances override earlier ones.
|
| 432 |
+
|
| 433 |
+
Returns:
|
| 434 |
+
FieldInfo: A merged FieldInfo instance.
|
| 435 |
+
"""
|
| 436 |
+
if len(field_infos) == 1:
|
| 437 |
+
# No merging necessary, but we still need to make a copy and apply the overrides
|
| 438 |
+
field_info = copy(field_infos[0])
|
| 439 |
+
field_info._attributes_set.update(overrides)
|
| 440 |
+
|
| 441 |
+
default_override = overrides.pop('default', PydanticUndefined)
|
| 442 |
+
if default_override is Ellipsis:
|
| 443 |
+
default_override = PydanticUndefined
|
| 444 |
+
if default_override is not PydanticUndefined:
|
| 445 |
+
field_info.default = default_override
|
| 446 |
+
|
| 447 |
+
for k, v in overrides.items():
|
| 448 |
+
setattr(field_info, k, v)
|
| 449 |
+
return field_info # type: ignore
|
| 450 |
+
|
| 451 |
+
merged_field_info_kwargs: dict[str, Any] = {}
|
| 452 |
+
metadata = {}
|
| 453 |
+
for field_info in field_infos:
|
| 454 |
+
attributes_set = field_info._attributes_set.copy()
|
| 455 |
+
|
| 456 |
+
try:
|
| 457 |
+
json_schema_extra = attributes_set.pop('json_schema_extra')
|
| 458 |
+
existing_json_schema_extra = merged_field_info_kwargs.get('json_schema_extra')
|
| 459 |
+
|
| 460 |
+
if existing_json_schema_extra is None:
|
| 461 |
+
merged_field_info_kwargs['json_schema_extra'] = json_schema_extra
|
| 462 |
+
if isinstance(existing_json_schema_extra, dict):
|
| 463 |
+
if isinstance(json_schema_extra, dict):
|
| 464 |
+
merged_field_info_kwargs['json_schema_extra'] = {
|
| 465 |
+
**existing_json_schema_extra,
|
| 466 |
+
**json_schema_extra,
|
| 467 |
+
}
|
| 468 |
+
if callable(json_schema_extra):
|
| 469 |
+
warn(
|
| 470 |
+
'Composing `dict` and `callable` type `json_schema_extra` is not supported.'
|
| 471 |
+
'The `callable` type is being ignored.'
|
| 472 |
+
"If you'd like support for this behavior, please open an issue on pydantic.",
|
| 473 |
+
PydanticJsonSchemaWarning,
|
| 474 |
+
)
|
| 475 |
+
elif callable(json_schema_extra):
|
| 476 |
+
# if ever there's a case of a callable, we'll just keep the last json schema extra spec
|
| 477 |
+
merged_field_info_kwargs['json_schema_extra'] = json_schema_extra
|
| 478 |
+
except KeyError:
|
| 479 |
+
pass
|
| 480 |
+
|
| 481 |
+
# later FieldInfo instances override everything except json_schema_extra from earlier FieldInfo instances
|
| 482 |
+
merged_field_info_kwargs.update(attributes_set)
|
| 483 |
+
|
| 484 |
+
for x in field_info.metadata:
|
| 485 |
+
if not isinstance(x, FieldInfo):
|
| 486 |
+
metadata[type(x)] = x
|
| 487 |
+
|
| 488 |
+
merged_field_info_kwargs.update(overrides)
|
| 489 |
+
field_info = FieldInfo(**merged_field_info_kwargs)
|
| 490 |
+
field_info.metadata = list(metadata.values())
|
| 491 |
+
return field_info
|
| 492 |
+
|
| 493 |
+
@staticmethod
|
| 494 |
+
def _from_dataclass_field(dc_field: DataclassField[Any]) -> FieldInfo:
|
| 495 |
+
"""Return a new `FieldInfo` instance from a `dataclasses.Field` instance.
|
| 496 |
+
|
| 497 |
+
Args:
|
| 498 |
+
dc_field: The `dataclasses.Field` instance to convert.
|
| 499 |
+
|
| 500 |
+
Returns:
|
| 501 |
+
The corresponding `FieldInfo` instance.
|
| 502 |
+
|
| 503 |
+
Raises:
|
| 504 |
+
TypeError: If any of the `FieldInfo` kwargs does not match the `dataclass.Field` kwargs.
|
| 505 |
+
"""
|
| 506 |
+
default = dc_field.default
|
| 507 |
+
if default is dataclasses.MISSING:
|
| 508 |
+
default = _Unset
|
| 509 |
+
|
| 510 |
+
if dc_field.default_factory is dataclasses.MISSING:
|
| 511 |
+
default_factory = _Unset
|
| 512 |
+
else:
|
| 513 |
+
default_factory = dc_field.default_factory
|
| 514 |
+
|
| 515 |
+
# use the `Field` function so in correct kwargs raise the correct `TypeError`
|
| 516 |
+
dc_field_metadata = {k: v for k, v in dc_field.metadata.items() if k in _FIELD_ARG_NAMES}
|
| 517 |
+
return Field(default=default, default_factory=default_factory, repr=dc_field.repr, **dc_field_metadata) # pyright: ignore[reportCallIssue]
|
| 518 |
+
|
| 519 |
+
@staticmethod
|
| 520 |
+
def _extract_metadata(annotation: type[Any] | None) -> tuple[type[Any] | None, list[Any]]:
|
| 521 |
+
"""Tries to extract metadata/constraints from an annotation if it uses `Annotated`.
|
| 522 |
+
|
| 523 |
+
Args:
|
| 524 |
+
annotation: The type hint annotation for which metadata has to be extracted.
|
| 525 |
+
|
| 526 |
+
Returns:
|
| 527 |
+
A tuple containing the extracted metadata type and the list of extra arguments.
|
| 528 |
+
"""
|
| 529 |
+
if annotation is not None:
|
| 530 |
+
if _typing_extra.is_annotated(annotation):
|
| 531 |
+
first_arg, *extra_args = typing_extensions.get_args(annotation)
|
| 532 |
+
return first_arg, list(extra_args)
|
| 533 |
+
|
| 534 |
+
return annotation, []
|
| 535 |
+
|
| 536 |
+
@staticmethod
|
| 537 |
+
def _collect_metadata(kwargs: dict[str, Any]) -> list[Any]:
|
| 538 |
+
"""Collect annotations from kwargs.
|
| 539 |
+
|
| 540 |
+
Args:
|
| 541 |
+
kwargs: Keyword arguments passed to the function.
|
| 542 |
+
|
| 543 |
+
Returns:
|
| 544 |
+
A list of metadata objects - a combination of `annotated_types.BaseMetadata` and
|
| 545 |
+
`PydanticMetadata`.
|
| 546 |
+
"""
|
| 547 |
+
metadata: list[Any] = []
|
| 548 |
+
general_metadata = {}
|
| 549 |
+
for key, value in list(kwargs.items()):
|
| 550 |
+
try:
|
| 551 |
+
marker = FieldInfo.metadata_lookup[key]
|
| 552 |
+
except KeyError:
|
| 553 |
+
continue
|
| 554 |
+
|
| 555 |
+
del kwargs[key]
|
| 556 |
+
if value is not None:
|
| 557 |
+
if marker is None:
|
| 558 |
+
general_metadata[key] = value
|
| 559 |
+
else:
|
| 560 |
+
metadata.append(marker(value))
|
| 561 |
+
if general_metadata:
|
| 562 |
+
metadata.append(_fields.pydantic_general_metadata(**general_metadata))
|
| 563 |
+
return metadata
|
| 564 |
+
|
| 565 |
+
@property
|
| 566 |
+
def deprecation_message(self) -> str | None:
|
| 567 |
+
"""The deprecation message to be emitted, or `None` if not set."""
|
| 568 |
+
if self.deprecated is None:
|
| 569 |
+
return None
|
| 570 |
+
if isinstance(self.deprecated, bool):
|
| 571 |
+
return 'deprecated' if self.deprecated else None
|
| 572 |
+
return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message
|
| 573 |
+
|
| 574 |
+
@property
|
| 575 |
+
def default_factory_takes_validated_data(self) -> bool | None:
|
| 576 |
+
"""Whether the provided default factory callable has a validated data parameter.
|
| 577 |
+
|
| 578 |
+
Returns `None` if no default factory is set.
|
| 579 |
+
"""
|
| 580 |
+
if self.default_factory is not None:
|
| 581 |
+
return _fields.takes_validated_data_argument(self.default_factory)
|
| 582 |
+
|
| 583 |
+
@overload
|
| 584 |
+
def get_default(
|
| 585 |
+
self, *, call_default_factory: Literal[True], validated_data: dict[str, Any] | None = None
|
| 586 |
+
) -> Any: ...
|
| 587 |
+
|
| 588 |
+
@overload
|
| 589 |
+
def get_default(self, *, call_default_factory: Literal[False] = ...) -> Any: ...
|
| 590 |
+
|
| 591 |
+
def get_default(self, *, call_default_factory: bool = False, validated_data: dict[str, Any] | None = None) -> Any:
|
| 592 |
+
"""Get the default value.
|
| 593 |
+
|
| 594 |
+
We expose an option for whether to call the default_factory (if present), as calling it may
|
| 595 |
+
result in side effects that we want to avoid. However, there are times when it really should
|
| 596 |
+
be called (namely, when instantiating a model via `model_construct`).
|
| 597 |
+
|
| 598 |
+
Args:
|
| 599 |
+
call_default_factory: Whether to call the default factory or not.
|
| 600 |
+
validated_data: The already validated data to be passed to the default factory.
|
| 601 |
+
|
| 602 |
+
Returns:
|
| 603 |
+
The default value, calling the default factory if requested or `None` if not set.
|
| 604 |
+
"""
|
| 605 |
+
if self.default_factory is None:
|
| 606 |
+
return _utils.smart_deepcopy(self.default)
|
| 607 |
+
elif call_default_factory:
|
| 608 |
+
if self.default_factory_takes_validated_data:
|
| 609 |
+
fac = cast('Callable[[dict[str, Any]], Any]', self.default_factory)
|
| 610 |
+
if validated_data is None:
|
| 611 |
+
raise ValueError(
|
| 612 |
+
"The default factory requires the 'validated_data' argument, which was not provided when calling 'get_default'."
|
| 613 |
+
)
|
| 614 |
+
return fac(validated_data)
|
| 615 |
+
else:
|
| 616 |
+
fac = cast('Callable[[], Any]', self.default_factory)
|
| 617 |
+
return fac()
|
| 618 |
+
else:
|
| 619 |
+
return None
|
| 620 |
+
|
| 621 |
+
def is_required(self) -> bool:
|
| 622 |
+
"""Check if the field is required (i.e., does not have a default value or factory).
|
| 623 |
+
|
| 624 |
+
Returns:
|
| 625 |
+
`True` if the field is required, `False` otherwise.
|
| 626 |
+
"""
|
| 627 |
+
return self.default is PydanticUndefined and self.default_factory is None
|
| 628 |
+
|
| 629 |
+
def rebuild_annotation(self) -> Any:
|
| 630 |
+
"""Attempts to rebuild the original annotation for use in function signatures.
|
| 631 |
+
|
| 632 |
+
If metadata is present, it adds it to the original annotation using
|
| 633 |
+
`Annotated`. Otherwise, it returns the original annotation as-is.
|
| 634 |
+
|
| 635 |
+
Note that because the metadata has been flattened, the original annotation
|
| 636 |
+
may not be reconstructed exactly as originally provided, e.g. if the original
|
| 637 |
+
type had unrecognized annotations, or was annotated with a call to `pydantic.Field`.
|
| 638 |
+
|
| 639 |
+
Returns:
|
| 640 |
+
The rebuilt annotation.
|
| 641 |
+
"""
|
| 642 |
+
if not self.metadata:
|
| 643 |
+
return self.annotation
|
| 644 |
+
else:
|
| 645 |
+
# Annotated arguments must be a tuple
|
| 646 |
+
return typing_extensions.Annotated[(self.annotation, *self.metadata)] # type: ignore
|
| 647 |
+
|
| 648 |
+
def apply_typevars_map(
|
| 649 |
+
self,
|
| 650 |
+
typevars_map: dict[Any, Any] | None,
|
| 651 |
+
globalns: GlobalsNamespace | None = None,
|
| 652 |
+
localns: MappingNamespace | None = None,
|
| 653 |
+
) -> None:
|
| 654 |
+
"""Apply a `typevars_map` to the annotation.
|
| 655 |
+
|
| 656 |
+
This method is used when analyzing parametrized generic types to replace typevars with their concrete types.
|
| 657 |
+
|
| 658 |
+
This method applies the `typevars_map` to the annotation in place.
|
| 659 |
+
|
| 660 |
+
Args:
|
| 661 |
+
typevars_map: A dictionary mapping type variables to their concrete types.
|
| 662 |
+
globalns: The globals namespace to use during type annotation evaluation.
|
| 663 |
+
localns: The locals namespace to use during type annotation evaluation.
|
| 664 |
+
|
| 665 |
+
See Also:
|
| 666 |
+
pydantic._internal._generics.replace_types is used for replacing the typevars with
|
| 667 |
+
their concrete types.
|
| 668 |
+
"""
|
| 669 |
+
annotation, _ = _typing_extra.try_eval_type(self.annotation, globalns, localns)
|
| 670 |
+
self.annotation = _generics.replace_types(annotation, typevars_map)
|
| 671 |
+
|
| 672 |
+
def __repr_args__(self) -> ReprArgs:
|
| 673 |
+
yield 'annotation', _repr.PlainRepr(_repr.display_as_type(self.annotation))
|
| 674 |
+
yield 'required', self.is_required()
|
| 675 |
+
|
| 676 |
+
for s in self.__slots__:
|
| 677 |
+
# TODO: properly make use of the protocol (https://rich.readthedocs.io/en/stable/pretty.html#rich-repr-protocol)
|
| 678 |
+
# By yielding a three-tuple:
|
| 679 |
+
if s in ('_attributes_set', 'annotation', 'evaluated'):
|
| 680 |
+
continue
|
| 681 |
+
elif s == 'metadata' and not self.metadata:
|
| 682 |
+
continue
|
| 683 |
+
elif s == 'repr' and self.repr is True:
|
| 684 |
+
continue
|
| 685 |
+
if s == 'frozen' and self.frozen is False:
|
| 686 |
+
continue
|
| 687 |
+
if s == 'validation_alias' and self.validation_alias == self.alias:
|
| 688 |
+
continue
|
| 689 |
+
if s == 'serialization_alias' and self.serialization_alias == self.alias:
|
| 690 |
+
continue
|
| 691 |
+
if s == 'default' and self.default is not PydanticUndefined:
|
| 692 |
+
yield 'default', self.default
|
| 693 |
+
elif s == 'default_factory' and self.default_factory is not None:
|
| 694 |
+
yield 'default_factory', _repr.PlainRepr(_repr.display_as_type(self.default_factory))
|
| 695 |
+
else:
|
| 696 |
+
value = getattr(self, s)
|
| 697 |
+
if value is not None and value is not PydanticUndefined:
|
| 698 |
+
yield s, value
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
class _EmptyKwargs(typing_extensions.TypedDict):
|
| 702 |
+
"""This class exists solely to ensure that type checking warns about passing `**extra` in `Field`."""
|
| 703 |
+
|
| 704 |
+
|
| 705 |
+
_DefaultValues = {
|
| 706 |
+
'default': ...,
|
| 707 |
+
'default_factory': None,
|
| 708 |
+
'alias': None,
|
| 709 |
+
'alias_priority': None,
|
| 710 |
+
'validation_alias': None,
|
| 711 |
+
'serialization_alias': None,
|
| 712 |
+
'title': None,
|
| 713 |
+
'description': None,
|
| 714 |
+
'examples': None,
|
| 715 |
+
'exclude': None,
|
| 716 |
+
'discriminator': None,
|
| 717 |
+
'json_schema_extra': None,
|
| 718 |
+
'frozen': None,
|
| 719 |
+
'validate_default': None,
|
| 720 |
+
'repr': True,
|
| 721 |
+
'init': None,
|
| 722 |
+
'init_var': None,
|
| 723 |
+
'kw_only': None,
|
| 724 |
+
'pattern': None,
|
| 725 |
+
'strict': None,
|
| 726 |
+
'gt': None,
|
| 727 |
+
'ge': None,
|
| 728 |
+
'lt': None,
|
| 729 |
+
'le': None,
|
| 730 |
+
'multiple_of': None,
|
| 731 |
+
'allow_inf_nan': None,
|
| 732 |
+
'max_digits': None,
|
| 733 |
+
'decimal_places': None,
|
| 734 |
+
'min_length': None,
|
| 735 |
+
'max_length': None,
|
| 736 |
+
'coerce_numbers_to_str': None,
|
| 737 |
+
}
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
_T = TypeVar('_T')
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
# NOTE: Actual return type is 'FieldInfo', but we want to help type checkers
|
| 744 |
+
# to understand the magic that happens at runtime with the following overloads:
|
| 745 |
+
@overload # type hint the return value as `Any` to avoid type checking regressions when using `...`.
|
| 746 |
+
def Field(
|
| 747 |
+
default: ellipsis, # noqa: F821 # TODO: use `_typing_extra.EllipsisType` when we drop Py3.9
|
| 748 |
+
*,
|
| 749 |
+
alias: str | None = _Unset,
|
| 750 |
+
alias_priority: int | None = _Unset,
|
| 751 |
+
validation_alias: str | AliasPath | AliasChoices | None = _Unset,
|
| 752 |
+
serialization_alias: str | None = _Unset,
|
| 753 |
+
title: str | None = _Unset,
|
| 754 |
+
field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
|
| 755 |
+
description: str | None = _Unset,
|
| 756 |
+
examples: list[Any] | None = _Unset,
|
| 757 |
+
exclude: bool | None = _Unset,
|
| 758 |
+
discriminator: str | types.Discriminator | None = _Unset,
|
| 759 |
+
deprecated: Deprecated | str | bool | None = _Unset,
|
| 760 |
+
json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
|
| 761 |
+
frozen: bool | None = _Unset,
|
| 762 |
+
validate_default: bool | None = _Unset,
|
| 763 |
+
repr: bool = _Unset,
|
| 764 |
+
init: bool | None = _Unset,
|
| 765 |
+
init_var: bool | None = _Unset,
|
| 766 |
+
kw_only: bool | None = _Unset,
|
| 767 |
+
pattern: str | typing.Pattern[str] | None = _Unset,
|
| 768 |
+
strict: bool | None = _Unset,
|
| 769 |
+
coerce_numbers_to_str: bool | None = _Unset,
|
| 770 |
+
gt: annotated_types.SupportsGt | None = _Unset,
|
| 771 |
+
ge: annotated_types.SupportsGe | None = _Unset,
|
| 772 |
+
lt: annotated_types.SupportsLt | None = _Unset,
|
| 773 |
+
le: annotated_types.SupportsLe | None = _Unset,
|
| 774 |
+
multiple_of: float | None = _Unset,
|
| 775 |
+
allow_inf_nan: bool | None = _Unset,
|
| 776 |
+
max_digits: int | None = _Unset,
|
| 777 |
+
decimal_places: int | None = _Unset,
|
| 778 |
+
min_length: int | None = _Unset,
|
| 779 |
+
max_length: int | None = _Unset,
|
| 780 |
+
union_mode: Literal['smart', 'left_to_right'] = _Unset,
|
| 781 |
+
fail_fast: bool | None = _Unset,
|
| 782 |
+
**extra: Unpack[_EmptyKwargs],
|
| 783 |
+
) -> Any: ...
|
| 784 |
+
@overload # `default` argument set
|
| 785 |
+
def Field(
|
| 786 |
+
default: _T,
|
| 787 |
+
*,
|
| 788 |
+
alias: str | None = _Unset,
|
| 789 |
+
alias_priority: int | None = _Unset,
|
| 790 |
+
validation_alias: str | AliasPath | AliasChoices | None = _Unset,
|
| 791 |
+
serialization_alias: str | None = _Unset,
|
| 792 |
+
title: str | None = _Unset,
|
| 793 |
+
field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
|
| 794 |
+
description: str | None = _Unset,
|
| 795 |
+
examples: list[Any] | None = _Unset,
|
| 796 |
+
exclude: bool | None = _Unset,
|
| 797 |
+
discriminator: str | types.Discriminator | None = _Unset,
|
| 798 |
+
deprecated: Deprecated | str | bool | None = _Unset,
|
| 799 |
+
json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
|
| 800 |
+
frozen: bool | None = _Unset,
|
| 801 |
+
validate_default: bool | None = _Unset,
|
| 802 |
+
repr: bool = _Unset,
|
| 803 |
+
init: bool | None = _Unset,
|
| 804 |
+
init_var: bool | None = _Unset,
|
| 805 |
+
kw_only: bool | None = _Unset,
|
| 806 |
+
pattern: str | typing.Pattern[str] | None = _Unset,
|
| 807 |
+
strict: bool | None = _Unset,
|
| 808 |
+
coerce_numbers_to_str: bool | None = _Unset,
|
| 809 |
+
gt: annotated_types.SupportsGt | None = _Unset,
|
| 810 |
+
ge: annotated_types.SupportsGe | None = _Unset,
|
| 811 |
+
lt: annotated_types.SupportsLt | None = _Unset,
|
| 812 |
+
le: annotated_types.SupportsLe | None = _Unset,
|
| 813 |
+
multiple_of: float | None = _Unset,
|
| 814 |
+
allow_inf_nan: bool | None = _Unset,
|
| 815 |
+
max_digits: int | None = _Unset,
|
| 816 |
+
decimal_places: int | None = _Unset,
|
| 817 |
+
min_length: int | None = _Unset,
|
| 818 |
+
max_length: int | None = _Unset,
|
| 819 |
+
union_mode: Literal['smart', 'left_to_right'] = _Unset,
|
| 820 |
+
fail_fast: bool | None = _Unset,
|
| 821 |
+
**extra: Unpack[_EmptyKwargs],
|
| 822 |
+
) -> _T: ...
|
| 823 |
+
@overload # `default_factory` argument set
|
| 824 |
+
def Field(
|
| 825 |
+
*,
|
| 826 |
+
default_factory: Callable[[], _T] | Callable[[dict[str, Any]], _T],
|
| 827 |
+
alias: str | None = _Unset,
|
| 828 |
+
alias_priority: int | None = _Unset,
|
| 829 |
+
validation_alias: str | AliasPath | AliasChoices | None = _Unset,
|
| 830 |
+
serialization_alias: str | None = _Unset,
|
| 831 |
+
title: str | None = _Unset,
|
| 832 |
+
field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
|
| 833 |
+
description: str | None = _Unset,
|
| 834 |
+
examples: list[Any] | None = _Unset,
|
| 835 |
+
exclude: bool | None = _Unset,
|
| 836 |
+
discriminator: str | types.Discriminator | None = _Unset,
|
| 837 |
+
deprecated: Deprecated | str | bool | None = _Unset,
|
| 838 |
+
json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
|
| 839 |
+
frozen: bool | None = _Unset,
|
| 840 |
+
validate_default: bool | None = _Unset,
|
| 841 |
+
repr: bool = _Unset,
|
| 842 |
+
init: bool | None = _Unset,
|
| 843 |
+
init_var: bool | None = _Unset,
|
| 844 |
+
kw_only: bool | None = _Unset,
|
| 845 |
+
pattern: str | typing.Pattern[str] | None = _Unset,
|
| 846 |
+
strict: bool | None = _Unset,
|
| 847 |
+
coerce_numbers_to_str: bool | None = _Unset,
|
| 848 |
+
gt: annotated_types.SupportsGt | None = _Unset,
|
| 849 |
+
ge: annotated_types.SupportsGe | None = _Unset,
|
| 850 |
+
lt: annotated_types.SupportsLt | None = _Unset,
|
| 851 |
+
le: annotated_types.SupportsLe | None = _Unset,
|
| 852 |
+
multiple_of: float | None = _Unset,
|
| 853 |
+
allow_inf_nan: bool | None = _Unset,
|
| 854 |
+
max_digits: int | None = _Unset,
|
| 855 |
+
decimal_places: int | None = _Unset,
|
| 856 |
+
min_length: int | None = _Unset,
|
| 857 |
+
max_length: int | None = _Unset,
|
| 858 |
+
union_mode: Literal['smart', 'left_to_right'] = _Unset,
|
| 859 |
+
fail_fast: bool | None = _Unset,
|
| 860 |
+
**extra: Unpack[_EmptyKwargs],
|
| 861 |
+
) -> _T: ...
|
| 862 |
+
@overload
|
| 863 |
+
def Field( # No default set
|
| 864 |
+
*,
|
| 865 |
+
alias: str | None = _Unset,
|
| 866 |
+
alias_priority: int | None = _Unset,
|
| 867 |
+
validation_alias: str | AliasPath | AliasChoices | None = _Unset,
|
| 868 |
+
serialization_alias: str | None = _Unset,
|
| 869 |
+
title: str | None = _Unset,
|
| 870 |
+
field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
|
| 871 |
+
description: str | None = _Unset,
|
| 872 |
+
examples: list[Any] | None = _Unset,
|
| 873 |
+
exclude: bool | None = _Unset,
|
| 874 |
+
discriminator: str | types.Discriminator | None = _Unset,
|
| 875 |
+
deprecated: Deprecated | str | bool | None = _Unset,
|
| 876 |
+
json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
|
| 877 |
+
frozen: bool | None = _Unset,
|
| 878 |
+
validate_default: bool | None = _Unset,
|
| 879 |
+
repr: bool = _Unset,
|
| 880 |
+
init: bool | None = _Unset,
|
| 881 |
+
init_var: bool | None = _Unset,
|
| 882 |
+
kw_only: bool | None = _Unset,
|
| 883 |
+
pattern: str | typing.Pattern[str] | None = _Unset,
|
| 884 |
+
strict: bool | None = _Unset,
|
| 885 |
+
coerce_numbers_to_str: bool | None = _Unset,
|
| 886 |
+
gt: annotated_types.SupportsGt | None = _Unset,
|
| 887 |
+
ge: annotated_types.SupportsGe | None = _Unset,
|
| 888 |
+
lt: annotated_types.SupportsLt | None = _Unset,
|
| 889 |
+
le: annotated_types.SupportsLe | None = _Unset,
|
| 890 |
+
multiple_of: float | None = _Unset,
|
| 891 |
+
allow_inf_nan: bool | None = _Unset,
|
| 892 |
+
max_digits: int | None = _Unset,
|
| 893 |
+
decimal_places: int | None = _Unset,
|
| 894 |
+
min_length: int | None = _Unset,
|
| 895 |
+
max_length: int | None = _Unset,
|
| 896 |
+
union_mode: Literal['smart', 'left_to_right'] = _Unset,
|
| 897 |
+
fail_fast: bool | None = _Unset,
|
| 898 |
+
**extra: Unpack[_EmptyKwargs],
|
| 899 |
+
) -> Any: ...
|
| 900 |
+
def Field( # noqa: C901
|
| 901 |
+
default: Any = PydanticUndefined,
|
| 902 |
+
*,
|
| 903 |
+
default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None = _Unset,
|
| 904 |
+
alias: str | None = _Unset,
|
| 905 |
+
alias_priority: int | None = _Unset,
|
| 906 |
+
validation_alias: str | AliasPath | AliasChoices | None = _Unset,
|
| 907 |
+
serialization_alias: str | None = _Unset,
|
| 908 |
+
title: str | None = _Unset,
|
| 909 |
+
field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
|
| 910 |
+
description: str | None = _Unset,
|
| 911 |
+
examples: list[Any] | None = _Unset,
|
| 912 |
+
exclude: bool | None = _Unset,
|
| 913 |
+
discriminator: str | types.Discriminator | None = _Unset,
|
| 914 |
+
deprecated: Deprecated | str | bool | None = _Unset,
|
| 915 |
+
json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
|
| 916 |
+
frozen: bool | None = _Unset,
|
| 917 |
+
validate_default: bool | None = _Unset,
|
| 918 |
+
repr: bool = _Unset,
|
| 919 |
+
init: bool | None = _Unset,
|
| 920 |
+
init_var: bool | None = _Unset,
|
| 921 |
+
kw_only: bool | None = _Unset,
|
| 922 |
+
pattern: str | typing.Pattern[str] | None = _Unset,
|
| 923 |
+
strict: bool | None = _Unset,
|
| 924 |
+
coerce_numbers_to_str: bool | None = _Unset,
|
| 925 |
+
gt: annotated_types.SupportsGt | None = _Unset,
|
| 926 |
+
ge: annotated_types.SupportsGe | None = _Unset,
|
| 927 |
+
lt: annotated_types.SupportsLt | None = _Unset,
|
| 928 |
+
le: annotated_types.SupportsLe | None = _Unset,
|
| 929 |
+
multiple_of: float | None = _Unset,
|
| 930 |
+
allow_inf_nan: bool | None = _Unset,
|
| 931 |
+
max_digits: int | None = _Unset,
|
| 932 |
+
decimal_places: int | None = _Unset,
|
| 933 |
+
min_length: int | None = _Unset,
|
| 934 |
+
max_length: int | None = _Unset,
|
| 935 |
+
union_mode: Literal['smart', 'left_to_right'] = _Unset,
|
| 936 |
+
fail_fast: bool | None = _Unset,
|
| 937 |
+
**extra: Unpack[_EmptyKwargs],
|
| 938 |
+
) -> Any:
|
| 939 |
+
"""Usage docs: https://docs.pydantic.dev/2.10/concepts/fields
|
| 940 |
+
|
| 941 |
+
Create a field for objects that can be configured.
|
| 942 |
+
|
| 943 |
+
Used to provide extra information about a field, either for the model schema or complex validation. Some arguments
|
| 944 |
+
apply only to number fields (`int`, `float`, `Decimal`) and some apply only to `str`.
|
| 945 |
+
|
| 946 |
+
Note:
|
| 947 |
+
- Any `_Unset` objects will be replaced by the corresponding value defined in the `_DefaultValues` dictionary. If a key for the `_Unset` object is not found in the `_DefaultValues` dictionary, it will default to `None`
|
| 948 |
+
|
| 949 |
+
Args:
|
| 950 |
+
default: Default value if the field is not set.
|
| 951 |
+
default_factory: A callable to generate the default value. The callable can either take 0 arguments
|
| 952 |
+
(in which case it is called as is) or a single argument containing the already validated data.
|
| 953 |
+
alias: The name to use for the attribute when validating or serializing by alias.
|
| 954 |
+
This is often used for things like converting between snake and camel case.
|
| 955 |
+
alias_priority: Priority of the alias. This affects whether an alias generator is used.
|
| 956 |
+
validation_alias: Like `alias`, but only affects validation, not serialization.
|
| 957 |
+
serialization_alias: Like `alias`, but only affects serialization, not validation.
|
| 958 |
+
title: Human-readable title.
|
| 959 |
+
field_title_generator: A callable that takes a field name and returns title for it.
|
| 960 |
+
description: Human-readable description.
|
| 961 |
+
examples: Example values for this field.
|
| 962 |
+
exclude: Whether to exclude the field from the model serialization.
|
| 963 |
+
discriminator: Field name or Discriminator for discriminating the type in a tagged union.
|
| 964 |
+
deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
|
| 965 |
+
or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
|
| 966 |
+
json_schema_extra: A dict or callable to provide extra JSON schema properties.
|
| 967 |
+
frozen: Whether the field is frozen. If true, attempts to change the value on an instance will raise an error.
|
| 968 |
+
validate_default: If `True`, apply validation to the default value every time you create an instance.
|
| 969 |
+
Otherwise, for performance reasons, the default value of the field is trusted and not validated.
|
| 970 |
+
repr: A boolean indicating whether to include the field in the `__repr__` output.
|
| 971 |
+
init: Whether the field should be included in the constructor of the dataclass.
|
| 972 |
+
(Only applies to dataclasses.)
|
| 973 |
+
init_var: Whether the field should _only_ be included in the constructor of the dataclass.
|
| 974 |
+
(Only applies to dataclasses.)
|
| 975 |
+
kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass.
|
| 976 |
+
(Only applies to dataclasses.)
|
| 977 |
+
coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode).
|
| 978 |
+
strict: If `True`, strict validation is applied to the field.
|
| 979 |
+
See [Strict Mode](../concepts/strict_mode.md) for details.
|
| 980 |
+
gt: Greater than. If set, value must be greater than this. Only applicable to numbers.
|
| 981 |
+
ge: Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers.
|
| 982 |
+
lt: Less than. If set, value must be less than this. Only applicable to numbers.
|
| 983 |
+
le: Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers.
|
| 984 |
+
multiple_of: Value must be a multiple of this. Only applicable to numbers.
|
| 985 |
+
min_length: Minimum length for iterables.
|
| 986 |
+
max_length: Maximum length for iterables.
|
| 987 |
+
pattern: Pattern for strings (a regular expression).
|
| 988 |
+
allow_inf_nan: Allow `inf`, `-inf`, `nan`. Only applicable to numbers.
|
| 989 |
+
max_digits: Maximum number of allow digits for strings.
|
| 990 |
+
decimal_places: Maximum number of decimal places allowed for numbers.
|
| 991 |
+
union_mode: The strategy to apply when validating a union. Can be `smart` (the default), or `left_to_right`.
|
| 992 |
+
See [Union Mode](../concepts/unions.md#union-modes) for details.
|
| 993 |
+
fail_fast: If `True`, validation will stop on the first error. If `False`, all validation errors will be collected.
|
| 994 |
+
This option can be applied only to iterable types (list, tuple, set, and frozenset).
|
| 995 |
+
extra: (Deprecated) Extra fields that will be included in the JSON schema.
|
| 996 |
+
|
| 997 |
+
!!! warning Deprecated
|
| 998 |
+
The `extra` kwargs is deprecated. Use `json_schema_extra` instead.
|
| 999 |
+
|
| 1000 |
+
Returns:
|
| 1001 |
+
A new [`FieldInfo`][pydantic.fields.FieldInfo]. The return annotation is `Any` so `Field` can be used on
|
| 1002 |
+
type-annotated fields without causing a type error.
|
| 1003 |
+
"""
|
| 1004 |
+
# Check deprecated and removed params from V1. This logic should eventually be removed.
|
| 1005 |
+
const = extra.pop('const', None) # type: ignore
|
| 1006 |
+
if const is not None:
|
| 1007 |
+
raise PydanticUserError('`const` is removed, use `Literal` instead', code='removed-kwargs')
|
| 1008 |
+
|
| 1009 |
+
min_items = extra.pop('min_items', None) # type: ignore
|
| 1010 |
+
if min_items is not None:
|
| 1011 |
+
warn('`min_items` is deprecated and will be removed, use `min_length` instead', DeprecationWarning)
|
| 1012 |
+
if min_length in (None, _Unset):
|
| 1013 |
+
min_length = min_items # type: ignore
|
| 1014 |
+
|
| 1015 |
+
max_items = extra.pop('max_items', None) # type: ignore
|
| 1016 |
+
if max_items is not None:
|
| 1017 |
+
warn('`max_items` is deprecated and will be removed, use `max_length` instead', DeprecationWarning)
|
| 1018 |
+
if max_length in (None, _Unset):
|
| 1019 |
+
max_length = max_items # type: ignore
|
| 1020 |
+
|
| 1021 |
+
unique_items = extra.pop('unique_items', None) # type: ignore
|
| 1022 |
+
if unique_items is not None:
|
| 1023 |
+
raise PydanticUserError(
|
| 1024 |
+
(
|
| 1025 |
+
'`unique_items` is removed, use `Set` instead'
|
| 1026 |
+
'(this feature is discussed in https://github.com/pydantic/pydantic-core/issues/296)'
|
| 1027 |
+
),
|
| 1028 |
+
code='removed-kwargs',
|
| 1029 |
+
)
|
| 1030 |
+
|
| 1031 |
+
allow_mutation = extra.pop('allow_mutation', None) # type: ignore
|
| 1032 |
+
if allow_mutation is not None:
|
| 1033 |
+
warn('`allow_mutation` is deprecated and will be removed. use `frozen` instead', DeprecationWarning)
|
| 1034 |
+
if allow_mutation is False:
|
| 1035 |
+
frozen = True
|
| 1036 |
+
|
| 1037 |
+
regex = extra.pop('regex', None) # type: ignore
|
| 1038 |
+
if regex is not None:
|
| 1039 |
+
raise PydanticUserError('`regex` is removed. use `pattern` instead', code='removed-kwargs')
|
| 1040 |
+
|
| 1041 |
+
if extra:
|
| 1042 |
+
warn(
|
| 1043 |
+
'Using extra keyword arguments on `Field` is deprecated and will be removed.'
|
| 1044 |
+
' Use `json_schema_extra` instead.'
|
| 1045 |
+
f' (Extra keys: {", ".join(k.__repr__() for k in extra.keys())})',
|
| 1046 |
+
DeprecationWarning,
|
| 1047 |
+
)
|
| 1048 |
+
if not json_schema_extra or json_schema_extra is _Unset:
|
| 1049 |
+
json_schema_extra = extra # type: ignore
|
| 1050 |
+
|
| 1051 |
+
if (
|
| 1052 |
+
validation_alias
|
| 1053 |
+
and validation_alias is not _Unset
|
| 1054 |
+
and not isinstance(validation_alias, (str, AliasChoices, AliasPath))
|
| 1055 |
+
):
|
| 1056 |
+
raise TypeError('Invalid `validation_alias` type. it should be `str`, `AliasChoices`, or `AliasPath`')
|
| 1057 |
+
|
| 1058 |
+
if serialization_alias in (_Unset, None) and isinstance(alias, str):
|
| 1059 |
+
serialization_alias = alias
|
| 1060 |
+
|
| 1061 |
+
if validation_alias in (_Unset, None):
|
| 1062 |
+
validation_alias = alias
|
| 1063 |
+
|
| 1064 |
+
include = extra.pop('include', None) # type: ignore
|
| 1065 |
+
if include is not None:
|
| 1066 |
+
warn('`include` is deprecated and does nothing. It will be removed, use `exclude` instead', DeprecationWarning)
|
| 1067 |
+
|
| 1068 |
+
return FieldInfo.from_field(
|
| 1069 |
+
default,
|
| 1070 |
+
default_factory=default_factory,
|
| 1071 |
+
alias=alias,
|
| 1072 |
+
alias_priority=alias_priority,
|
| 1073 |
+
validation_alias=validation_alias,
|
| 1074 |
+
serialization_alias=serialization_alias,
|
| 1075 |
+
title=title,
|
| 1076 |
+
field_title_generator=field_title_generator,
|
| 1077 |
+
description=description,
|
| 1078 |
+
examples=examples,
|
| 1079 |
+
exclude=exclude,
|
| 1080 |
+
discriminator=discriminator,
|
| 1081 |
+
deprecated=deprecated,
|
| 1082 |
+
json_schema_extra=json_schema_extra,
|
| 1083 |
+
frozen=frozen,
|
| 1084 |
+
pattern=pattern,
|
| 1085 |
+
validate_default=validate_default,
|
| 1086 |
+
repr=repr,
|
| 1087 |
+
init=init,
|
| 1088 |
+
init_var=init_var,
|
| 1089 |
+
kw_only=kw_only,
|
| 1090 |
+
coerce_numbers_to_str=coerce_numbers_to_str,
|
| 1091 |
+
strict=strict,
|
| 1092 |
+
gt=gt,
|
| 1093 |
+
ge=ge,
|
| 1094 |
+
lt=lt,
|
| 1095 |
+
le=le,
|
| 1096 |
+
multiple_of=multiple_of,
|
| 1097 |
+
min_length=min_length,
|
| 1098 |
+
max_length=max_length,
|
| 1099 |
+
allow_inf_nan=allow_inf_nan,
|
| 1100 |
+
max_digits=max_digits,
|
| 1101 |
+
decimal_places=decimal_places,
|
| 1102 |
+
union_mode=union_mode,
|
| 1103 |
+
fail_fast=fail_fast,
|
| 1104 |
+
)
|
| 1105 |
+
|
| 1106 |
+
|
| 1107 |
+
_FIELD_ARG_NAMES = set(inspect.signature(Field).parameters)
|
| 1108 |
+
_FIELD_ARG_NAMES.remove('extra') # do not include the varkwargs parameter
|
| 1109 |
+
|
| 1110 |
+
|
| 1111 |
+
class ModelPrivateAttr(_repr.Representation):
|
| 1112 |
+
"""A descriptor for private attributes in class models.
|
| 1113 |
+
|
| 1114 |
+
!!! warning
|
| 1115 |
+
You generally shouldn't be creating `ModelPrivateAttr` instances directly, instead use
|
| 1116 |
+
`pydantic.fields.PrivateAttr`. (This is similar to `FieldInfo` vs. `Field`.)
|
| 1117 |
+
|
| 1118 |
+
Attributes:
|
| 1119 |
+
default: The default value of the attribute if not provided.
|
| 1120 |
+
default_factory: A callable function that generates the default value of the
|
| 1121 |
+
attribute if not provided.
|
| 1122 |
+
"""
|
| 1123 |
+
|
| 1124 |
+
__slots__ = ('default', 'default_factory')
|
| 1125 |
+
|
| 1126 |
+
def __init__(
|
| 1127 |
+
self, default: Any = PydanticUndefined, *, default_factory: typing.Callable[[], Any] | None = None
|
| 1128 |
+
) -> None:
|
| 1129 |
+
if default is Ellipsis:
|
| 1130 |
+
self.default = PydanticUndefined
|
| 1131 |
+
else:
|
| 1132 |
+
self.default = default
|
| 1133 |
+
self.default_factory = default_factory
|
| 1134 |
+
|
| 1135 |
+
if not typing.TYPE_CHECKING:
|
| 1136 |
+
# We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access
|
| 1137 |
+
|
| 1138 |
+
def __getattr__(self, item: str) -> Any:
|
| 1139 |
+
"""This function improves compatibility with custom descriptors by ensuring delegation happens
|
| 1140 |
+
as expected when the default value of a private attribute is a descriptor.
|
| 1141 |
+
"""
|
| 1142 |
+
if item in {'__get__', '__set__', '__delete__'}:
|
| 1143 |
+
if hasattr(self.default, item):
|
| 1144 |
+
return getattr(self.default, item)
|
| 1145 |
+
raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')
|
| 1146 |
+
|
| 1147 |
+
def __set_name__(self, cls: type[Any], name: str) -> None:
|
| 1148 |
+
"""Preserve `__set_name__` protocol defined in https://peps.python.org/pep-0487."""
|
| 1149 |
+
default = self.default
|
| 1150 |
+
if default is PydanticUndefined:
|
| 1151 |
+
return
|
| 1152 |
+
set_name = getattr(default, '__set_name__', None)
|
| 1153 |
+
if callable(set_name):
|
| 1154 |
+
set_name(cls, name)
|
| 1155 |
+
|
| 1156 |
+
def get_default(self) -> Any:
|
| 1157 |
+
"""Retrieve the default value of the object.
|
| 1158 |
+
|
| 1159 |
+
If `self.default_factory` is `None`, the method will return a deep copy of the `self.default` object.
|
| 1160 |
+
|
| 1161 |
+
If `self.default_factory` is not `None`, it will call `self.default_factory` and return the value returned.
|
| 1162 |
+
|
| 1163 |
+
Returns:
|
| 1164 |
+
The default value of the object.
|
| 1165 |
+
"""
|
| 1166 |
+
return _utils.smart_deepcopy(self.default) if self.default_factory is None else self.default_factory()
|
| 1167 |
+
|
| 1168 |
+
def __eq__(self, other: Any) -> bool:
|
| 1169 |
+
return isinstance(other, self.__class__) and (self.default, self.default_factory) == (
|
| 1170 |
+
other.default,
|
| 1171 |
+
other.default_factory,
|
| 1172 |
+
)
|
| 1173 |
+
|
| 1174 |
+
|
| 1175 |
+
# NOTE: Actual return type is 'ModelPrivateAttr', but we want to help type checkers
|
| 1176 |
+
# to understand the magic that happens at runtime.
|
| 1177 |
+
@overload # `default` argument set
|
| 1178 |
+
def PrivateAttr(
|
| 1179 |
+
default: _T,
|
| 1180 |
+
*,
|
| 1181 |
+
init: Literal[False] = False,
|
| 1182 |
+
) -> _T: ...
|
| 1183 |
+
@overload # `default_factory` argument set
|
| 1184 |
+
def PrivateAttr(
|
| 1185 |
+
*,
|
| 1186 |
+
default_factory: Callable[[], _T],
|
| 1187 |
+
init: Literal[False] = False,
|
| 1188 |
+
) -> _T: ...
|
| 1189 |
+
@overload # No default set
|
| 1190 |
+
def PrivateAttr(
|
| 1191 |
+
*,
|
| 1192 |
+
init: Literal[False] = False,
|
| 1193 |
+
) -> Any: ...
|
| 1194 |
+
def PrivateAttr(
|
| 1195 |
+
default: Any = PydanticUndefined,
|
| 1196 |
+
*,
|
| 1197 |
+
default_factory: Callable[[], Any] | None = None,
|
| 1198 |
+
init: Literal[False] = False,
|
| 1199 |
+
) -> Any:
|
| 1200 |
+
"""Usage docs: https://docs.pydantic.dev/2.10/concepts/models/#private-model-attributes
|
| 1201 |
+
|
| 1202 |
+
Indicates that an attribute is intended for private use and not handled during normal validation/serialization.
|
| 1203 |
+
|
| 1204 |
+
Private attributes are not validated by Pydantic, so it's up to you to ensure they are used in a type-safe manner.
|
| 1205 |
+
|
| 1206 |
+
Private attributes are stored in `__private_attributes__` on the model.
|
| 1207 |
+
|
| 1208 |
+
Args:
|
| 1209 |
+
default: The attribute's default value. Defaults to Undefined.
|
| 1210 |
+
default_factory: Callable that will be
|
| 1211 |
+
called when a default value is needed for this attribute.
|
| 1212 |
+
If both `default` and `default_factory` are set, an error will be raised.
|
| 1213 |
+
init: Whether the attribute should be included in the constructor of the dataclass. Always `False`.
|
| 1214 |
+
|
| 1215 |
+
Returns:
|
| 1216 |
+
An instance of [`ModelPrivateAttr`][pydantic.fields.ModelPrivateAttr] class.
|
| 1217 |
+
|
| 1218 |
+
Raises:
|
| 1219 |
+
ValueError: If both `default` and `default_factory` are set.
|
| 1220 |
+
"""
|
| 1221 |
+
if default is not PydanticUndefined and default_factory is not None:
|
| 1222 |
+
raise TypeError('cannot specify both default and default_factory')
|
| 1223 |
+
|
| 1224 |
+
return ModelPrivateAttr(
|
| 1225 |
+
default,
|
| 1226 |
+
default_factory=default_factory,
|
| 1227 |
+
)
|
| 1228 |
+
|
| 1229 |
+
|
| 1230 |
+
@dataclasses.dataclass(**_internal_dataclass.slots_true)
|
| 1231 |
+
class ComputedFieldInfo:
|
| 1232 |
+
"""A container for data from `@computed_field` so that we can access it while building the pydantic-core schema.
|
| 1233 |
+
|
| 1234 |
+
Attributes:
|
| 1235 |
+
decorator_repr: A class variable representing the decorator string, '@computed_field'.
|
| 1236 |
+
wrapped_property: The wrapped computed field property.
|
| 1237 |
+
return_type: The type of the computed field property's return value.
|
| 1238 |
+
alias: The alias of the property to be used during serialization.
|
| 1239 |
+
alias_priority: The priority of the alias. This affects whether an alias generator is used.
|
| 1240 |
+
title: Title of the computed field to include in the serialization JSON schema.
|
| 1241 |
+
field_title_generator: A callable that takes a field name and returns title for it.
|
| 1242 |
+
description: Description of the computed field to include in the serialization JSON schema.
|
| 1243 |
+
deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
|
| 1244 |
+
or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
|
| 1245 |
+
examples: Example values of the computed field to include in the serialization JSON schema.
|
| 1246 |
+
json_schema_extra: A dict or callable to provide extra JSON schema properties.
|
| 1247 |
+
repr: A boolean indicating whether to include the field in the __repr__ output.
|
| 1248 |
+
"""
|
| 1249 |
+
|
| 1250 |
+
decorator_repr: ClassVar[str] = '@computed_field'
|
| 1251 |
+
wrapped_property: property
|
| 1252 |
+
return_type: Any
|
| 1253 |
+
alias: str | None
|
| 1254 |
+
alias_priority: int | None
|
| 1255 |
+
title: str | None
|
| 1256 |
+
field_title_generator: typing.Callable[[str, ComputedFieldInfo], str] | None
|
| 1257 |
+
description: str | None
|
| 1258 |
+
deprecated: Deprecated | str | bool | None
|
| 1259 |
+
examples: list[Any] | None
|
| 1260 |
+
json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None
|
| 1261 |
+
repr: bool
|
| 1262 |
+
|
| 1263 |
+
@property
|
| 1264 |
+
def deprecation_message(self) -> str | None:
|
| 1265 |
+
"""The deprecation message to be emitted, or `None` if not set."""
|
| 1266 |
+
if self.deprecated is None:
|
| 1267 |
+
return None
|
| 1268 |
+
if isinstance(self.deprecated, bool):
|
| 1269 |
+
return 'deprecated' if self.deprecated else None
|
| 1270 |
+
return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message
|
| 1271 |
+
|
| 1272 |
+
|
| 1273 |
+
def _wrapped_property_is_private(property_: cached_property | property) -> bool: # type: ignore
|
| 1274 |
+
"""Returns true if provided property is private, False otherwise."""
|
| 1275 |
+
wrapped_name: str = ''
|
| 1276 |
+
|
| 1277 |
+
if isinstance(property_, property):
|
| 1278 |
+
wrapped_name = getattr(property_.fget, '__name__', '')
|
| 1279 |
+
elif isinstance(property_, cached_property): # type: ignore
|
| 1280 |
+
wrapped_name = getattr(property_.func, '__name__', '') # type: ignore
|
| 1281 |
+
|
| 1282 |
+
return wrapped_name.startswith('_') and not wrapped_name.startswith('__')
|
| 1283 |
+
|
| 1284 |
+
|
| 1285 |
+
# this should really be `property[T], cached_property[T]` but property is not generic unlike cached_property
|
| 1286 |
+
# See https://github.com/python/typing/issues/985 and linked issues
|
| 1287 |
+
PropertyT = typing.TypeVar('PropertyT')
|
| 1288 |
+
|
| 1289 |
+
|
| 1290 |
+
@typing.overload
|
| 1291 |
+
def computed_field(
|
| 1292 |
+
*,
|
| 1293 |
+
alias: str | None = None,
|
| 1294 |
+
alias_priority: int | None = None,
|
| 1295 |
+
title: str | None = None,
|
| 1296 |
+
field_title_generator: typing.Callable[[str, ComputedFieldInfo], str] | None = None,
|
| 1297 |
+
description: str | None = None,
|
| 1298 |
+
deprecated: Deprecated | str | bool | None = None,
|
| 1299 |
+
examples: list[Any] | None = None,
|
| 1300 |
+
json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None = None,
|
| 1301 |
+
repr: bool = True,
|
| 1302 |
+
return_type: Any = PydanticUndefined,
|
| 1303 |
+
) -> typing.Callable[[PropertyT], PropertyT]: ...
|
| 1304 |
+
|
| 1305 |
+
|
| 1306 |
+
@typing.overload
|
| 1307 |
+
def computed_field(__func: PropertyT) -> PropertyT: ...
|
| 1308 |
+
|
| 1309 |
+
|
| 1310 |
+
def computed_field(
|
| 1311 |
+
func: PropertyT | None = None,
|
| 1312 |
+
/,
|
| 1313 |
+
*,
|
| 1314 |
+
alias: str | None = None,
|
| 1315 |
+
alias_priority: int | None = None,
|
| 1316 |
+
title: str | None = None,
|
| 1317 |
+
field_title_generator: typing.Callable[[str, ComputedFieldInfo], str] | None = None,
|
| 1318 |
+
description: str | None = None,
|
| 1319 |
+
deprecated: Deprecated | str | bool | None = None,
|
| 1320 |
+
examples: list[Any] | None = None,
|
| 1321 |
+
json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None = None,
|
| 1322 |
+
repr: bool | None = None,
|
| 1323 |
+
return_type: Any = PydanticUndefined,
|
| 1324 |
+
) -> PropertyT | typing.Callable[[PropertyT], PropertyT]:
|
| 1325 |
+
"""Usage docs: https://docs.pydantic.dev/2.10/concepts/fields#the-computed_field-decorator
|
| 1326 |
+
|
| 1327 |
+
Decorator to include `property` and `cached_property` when serializing models or dataclasses.
|
| 1328 |
+
|
| 1329 |
+
This is useful for fields that are computed from other fields, or for fields that are expensive to compute and should be cached.
|
| 1330 |
+
|
| 1331 |
+
```python
|
| 1332 |
+
from pydantic import BaseModel, computed_field
|
| 1333 |
+
|
| 1334 |
+
class Rectangle(BaseModel):
|
| 1335 |
+
width: int
|
| 1336 |
+
length: int
|
| 1337 |
+
|
| 1338 |
+
@computed_field
|
| 1339 |
+
@property
|
| 1340 |
+
def area(self) -> int:
|
| 1341 |
+
return self.width * self.length
|
| 1342 |
+
|
| 1343 |
+
print(Rectangle(width=3, length=2).model_dump())
|
| 1344 |
+
#> {'width': 3, 'length': 2, 'area': 6}
|
| 1345 |
+
```
|
| 1346 |
+
|
| 1347 |
+
If applied to functions not yet decorated with `@property` or `@cached_property`, the function is
|
| 1348 |
+
automatically wrapped with `property`. Although this is more concise, you will lose IntelliSense in your IDE,
|
| 1349 |
+
and confuse static type checkers, thus explicit use of `@property` is recommended.
|
| 1350 |
+
|
| 1351 |
+
!!! warning "Mypy Warning"
|
| 1352 |
+
Even with the `@property` or `@cached_property` applied to your function before `@computed_field`,
|
| 1353 |
+
mypy may throw a `Decorated property not supported` error.
|
| 1354 |
+
See [mypy issue #1362](https://github.com/python/mypy/issues/1362), for more information.
|
| 1355 |
+
To avoid this error message, add `# type: ignore[misc]` to the `@computed_field` line.
|
| 1356 |
+
|
| 1357 |
+
[pyright](https://github.com/microsoft/pyright) supports `@computed_field` without error.
|
| 1358 |
+
|
| 1359 |
+
```python
|
| 1360 |
+
import random
|
| 1361 |
+
|
| 1362 |
+
from pydantic import BaseModel, computed_field
|
| 1363 |
+
|
| 1364 |
+
class Square(BaseModel):
|
| 1365 |
+
width: float
|
| 1366 |
+
|
| 1367 |
+
@computed_field
|
| 1368 |
+
def area(self) -> float: # converted to a `property` by `computed_field`
|
| 1369 |
+
return round(self.width**2, 2)
|
| 1370 |
+
|
| 1371 |
+
@area.setter
|
| 1372 |
+
def area(self, new_area: float) -> None:
|
| 1373 |
+
self.width = new_area**0.5
|
| 1374 |
+
|
| 1375 |
+
@computed_field(alias='the magic number', repr=False)
|
| 1376 |
+
def random_number(self) -> int:
|
| 1377 |
+
return random.randint(0, 1_000)
|
| 1378 |
+
|
| 1379 |
+
square = Square(width=1.3)
|
| 1380 |
+
|
| 1381 |
+
# `random_number` does not appear in representation
|
| 1382 |
+
print(repr(square))
|
| 1383 |
+
#> Square(width=1.3, area=1.69)
|
| 1384 |
+
|
| 1385 |
+
print(square.random_number)
|
| 1386 |
+
#> 3
|
| 1387 |
+
|
| 1388 |
+
square.area = 4
|
| 1389 |
+
|
| 1390 |
+
print(square.model_dump_json(by_alias=True))
|
| 1391 |
+
#> {"width":2.0,"area":4.0,"the magic number":3}
|
| 1392 |
+
```
|
| 1393 |
+
|
| 1394 |
+
!!! warning "Overriding with `computed_field`"
|
| 1395 |
+
You can't override a field from a parent class with a `computed_field` in the child class.
|
| 1396 |
+
`mypy` complains about this behavior if allowed, and `dataclasses` doesn't allow this pattern either.
|
| 1397 |
+
See the example below:
|
| 1398 |
+
|
| 1399 |
+
```python
|
| 1400 |
+
from pydantic import BaseModel, computed_field
|
| 1401 |
+
|
| 1402 |
+
class Parent(BaseModel):
|
| 1403 |
+
a: str
|
| 1404 |
+
|
| 1405 |
+
try:
|
| 1406 |
+
|
| 1407 |
+
class Child(Parent):
|
| 1408 |
+
@computed_field
|
| 1409 |
+
@property
|
| 1410 |
+
def a(self) -> str:
|
| 1411 |
+
return 'new a'
|
| 1412 |
+
|
| 1413 |
+
except ValueError as e:
|
| 1414 |
+
print(repr(e))
|
| 1415 |
+
#> ValueError("you can't override a field with a computed field")
|
| 1416 |
+
```
|
| 1417 |
+
|
| 1418 |
+
Private properties decorated with `@computed_field` have `repr=False` by default.
|
| 1419 |
+
|
| 1420 |
+
```python
|
| 1421 |
+
from functools import cached_property
|
| 1422 |
+
|
| 1423 |
+
from pydantic import BaseModel, computed_field
|
| 1424 |
+
|
| 1425 |
+
class Model(BaseModel):
|
| 1426 |
+
foo: int
|
| 1427 |
+
|
| 1428 |
+
@computed_field
|
| 1429 |
+
@cached_property
|
| 1430 |
+
def _private_cached_property(self) -> int:
|
| 1431 |
+
return -self.foo
|
| 1432 |
+
|
| 1433 |
+
@computed_field
|
| 1434 |
+
@property
|
| 1435 |
+
def _private_property(self) -> int:
|
| 1436 |
+
return -self.foo
|
| 1437 |
+
|
| 1438 |
+
m = Model(foo=1)
|
| 1439 |
+
print(repr(m))
|
| 1440 |
+
#> Model(foo=1)
|
| 1441 |
+
```
|
| 1442 |
+
|
| 1443 |
+
Args:
|
| 1444 |
+
func: the function to wrap.
|
| 1445 |
+
alias: alias to use when serializing this computed field, only used when `by_alias=True`
|
| 1446 |
+
alias_priority: priority of the alias. This affects whether an alias generator is used
|
| 1447 |
+
title: Title to use when including this computed field in JSON Schema
|
| 1448 |
+
field_title_generator: A callable that takes a field name and returns title for it.
|
| 1449 |
+
description: Description to use when including this computed field in JSON Schema, defaults to the function's
|
| 1450 |
+
docstring
|
| 1451 |
+
deprecated: A deprecation message (or an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport).
|
| 1452 |
+
to be emitted when accessing the field. Or a boolean. This will automatically be set if the property is decorated with the
|
| 1453 |
+
`deprecated` decorator.
|
| 1454 |
+
examples: Example values to use when including this computed field in JSON Schema
|
| 1455 |
+
json_schema_extra: A dict or callable to provide extra JSON schema properties.
|
| 1456 |
+
repr: whether to include this computed field in model repr.
|
| 1457 |
+
Default is `False` for private properties and `True` for public properties.
|
| 1458 |
+
return_type: optional return for serialization logic to expect when serializing to JSON, if included
|
| 1459 |
+
this must be correct, otherwise a `TypeError` is raised.
|
| 1460 |
+
If you don't include a return type Any is used, which does runtime introspection to handle arbitrary
|
| 1461 |
+
objects.
|
| 1462 |
+
|
| 1463 |
+
Returns:
|
| 1464 |
+
A proxy wrapper for the property.
|
| 1465 |
+
"""
|
| 1466 |
+
|
| 1467 |
+
def dec(f: Any) -> Any:
|
| 1468 |
+
nonlocal description, deprecated, return_type, alias_priority
|
| 1469 |
+
unwrapped = _decorators.unwrap_wrapped_function(f)
|
| 1470 |
+
|
| 1471 |
+
if description is None and unwrapped.__doc__:
|
| 1472 |
+
description = inspect.cleandoc(unwrapped.__doc__)
|
| 1473 |
+
|
| 1474 |
+
if deprecated is None and hasattr(unwrapped, '__deprecated__'):
|
| 1475 |
+
deprecated = unwrapped.__deprecated__
|
| 1476 |
+
|
| 1477 |
+
# if the function isn't already decorated with `@property` (or another descriptor), then we wrap it now
|
| 1478 |
+
f = _decorators.ensure_property(f)
|
| 1479 |
+
alias_priority = (alias_priority or 2) if alias is not None else None
|
| 1480 |
+
|
| 1481 |
+
if repr is None:
|
| 1482 |
+
repr_: bool = not _wrapped_property_is_private(property_=f)
|
| 1483 |
+
else:
|
| 1484 |
+
repr_ = repr
|
| 1485 |
+
|
| 1486 |
+
dec_info = ComputedFieldInfo(
|
| 1487 |
+
f,
|
| 1488 |
+
return_type,
|
| 1489 |
+
alias,
|
| 1490 |
+
alias_priority,
|
| 1491 |
+
title,
|
| 1492 |
+
field_title_generator,
|
| 1493 |
+
description,
|
| 1494 |
+
deprecated,
|
| 1495 |
+
examples,
|
| 1496 |
+
json_schema_extra,
|
| 1497 |
+
repr_,
|
| 1498 |
+
)
|
| 1499 |
+
return _decorators.PydanticDescriptorProxy(f, dec_info)
|
| 1500 |
+
|
| 1501 |
+
if func is None:
|
| 1502 |
+
return dec
|
| 1503 |
+
else:
|
| 1504 |
+
return dec(func)
|
vllm/lib/python3.10/site-packages/pydantic/functional_serializers.py
ADDED
|
@@ -0,0 +1,449 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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functools import partial, partialmethod
|
| 7 |
+
from typing import TYPE_CHECKING, Any, Callable, TypeVar, overload
|
| 8 |
+
|
| 9 |
+
from pydantic_core import PydanticUndefined, core_schema
|
| 10 |
+
from pydantic_core.core_schema import SerializationInfo, SerializerFunctionWrapHandler, WhenUsed
|
| 11 |
+
from typing_extensions import Annotated, Literal, TypeAlias
|
| 12 |
+
|
| 13 |
+
from . import PydanticUndefinedAnnotation
|
| 14 |
+
from ._internal import _decorators, _internal_dataclass
|
| 15 |
+
from .annotated_handlers import GetCoreSchemaHandler
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@dataclasses.dataclass(**_internal_dataclass.slots_true, frozen=True)
|
| 19 |
+
class PlainSerializer:
|
| 20 |
+
"""Plain serializers use a function to modify the output of serialization.
|
| 21 |
+
|
| 22 |
+
This is particularly helpful when you want to customize the serialization for annotated types.
|
| 23 |
+
Consider an input of `list`, which will be serialized into a space-delimited string.
|
| 24 |
+
|
| 25 |
+
```python
|
| 26 |
+
from typing import List
|
| 27 |
+
|
| 28 |
+
from typing_extensions import Annotated
|
| 29 |
+
|
| 30 |
+
from pydantic import BaseModel, PlainSerializer
|
| 31 |
+
|
| 32 |
+
CustomStr = Annotated[
|
| 33 |
+
List, PlainSerializer(lambda x: ' '.join(x), return_type=str)
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
class StudentModel(BaseModel):
|
| 37 |
+
courses: CustomStr
|
| 38 |
+
|
| 39 |
+
student = StudentModel(courses=['Math', 'Chemistry', 'English'])
|
| 40 |
+
print(student.model_dump())
|
| 41 |
+
#> {'courses': 'Math Chemistry English'}
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
Attributes:
|
| 45 |
+
func: The serializer function.
|
| 46 |
+
return_type: The return type for the function. If omitted it will be inferred from the type annotation.
|
| 47 |
+
when_used: Determines when this serializer should be used. Accepts a string with values `'always'`,
|
| 48 |
+
`'unless-none'`, `'json'`, and `'json-unless-none'`. Defaults to 'always'.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
func: core_schema.SerializerFunction
|
| 52 |
+
return_type: Any = PydanticUndefined
|
| 53 |
+
when_used: WhenUsed = 'always'
|
| 54 |
+
|
| 55 |
+
def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
|
| 56 |
+
"""Gets the Pydantic core schema.
|
| 57 |
+
|
| 58 |
+
Args:
|
| 59 |
+
source_type: The source type.
|
| 60 |
+
handler: The `GetCoreSchemaHandler` instance.
|
| 61 |
+
|
| 62 |
+
Returns:
|
| 63 |
+
The Pydantic core schema.
|
| 64 |
+
"""
|
| 65 |
+
schema = handler(source_type)
|
| 66 |
+
try:
|
| 67 |
+
# Do not pass in globals as the function could be defined in a different module.
|
| 68 |
+
# Instead, let `get_function_return_type` infer the globals to use, but still pass
|
| 69 |
+
# in locals that may contain a parent/rebuild namespace:
|
| 70 |
+
return_type = _decorators.get_function_return_type(
|
| 71 |
+
self.func,
|
| 72 |
+
self.return_type,
|
| 73 |
+
localns=handler._get_types_namespace().locals,
|
| 74 |
+
)
|
| 75 |
+
except NameError as e:
|
| 76 |
+
raise PydanticUndefinedAnnotation.from_name_error(e) from e
|
| 77 |
+
return_schema = None if return_type is PydanticUndefined else handler.generate_schema(return_type)
|
| 78 |
+
schema['serialization'] = core_schema.plain_serializer_function_ser_schema(
|
| 79 |
+
function=self.func,
|
| 80 |
+
info_arg=_decorators.inspect_annotated_serializer(self.func, 'plain'),
|
| 81 |
+
return_schema=return_schema,
|
| 82 |
+
when_used=self.when_used,
|
| 83 |
+
)
|
| 84 |
+
return schema
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@dataclasses.dataclass(**_internal_dataclass.slots_true, frozen=True)
|
| 88 |
+
class WrapSerializer:
|
| 89 |
+
"""Wrap serializers receive the raw inputs along with a handler function that applies the standard serialization
|
| 90 |
+
logic, and can modify the resulting value before returning it as the final output of serialization.
|
| 91 |
+
|
| 92 |
+
For example, here's a scenario in which a wrap serializer transforms timezones to UTC **and** utilizes the existing `datetime` serialization logic.
|
| 93 |
+
|
| 94 |
+
```python
|
| 95 |
+
from datetime import datetime, timezone
|
| 96 |
+
from typing import Any, Dict
|
| 97 |
+
|
| 98 |
+
from typing_extensions import Annotated
|
| 99 |
+
|
| 100 |
+
from pydantic import BaseModel, WrapSerializer
|
| 101 |
+
|
| 102 |
+
class EventDatetime(BaseModel):
|
| 103 |
+
start: datetime
|
| 104 |
+
end: datetime
|
| 105 |
+
|
| 106 |
+
def convert_to_utc(value: Any, handler, info) -> Dict[str, datetime]:
|
| 107 |
+
# Note that `handler` can actually help serialize the `value` for
|
| 108 |
+
# further custom serialization in case it's a subclass.
|
| 109 |
+
partial_result = handler(value, info)
|
| 110 |
+
if info.mode == 'json':
|
| 111 |
+
return {
|
| 112 |
+
k: datetime.fromisoformat(v).astimezone(timezone.utc)
|
| 113 |
+
for k, v in partial_result.items()
|
| 114 |
+
}
|
| 115 |
+
return {k: v.astimezone(timezone.utc) for k, v in partial_result.items()}
|
| 116 |
+
|
| 117 |
+
UTCEventDatetime = Annotated[EventDatetime, WrapSerializer(convert_to_utc)]
|
| 118 |
+
|
| 119 |
+
class EventModel(BaseModel):
|
| 120 |
+
event_datetime: UTCEventDatetime
|
| 121 |
+
|
| 122 |
+
dt = EventDatetime(
|
| 123 |
+
start='2024-01-01T07:00:00-08:00', end='2024-01-03T20:00:00+06:00'
|
| 124 |
+
)
|
| 125 |
+
event = EventModel(event_datetime=dt)
|
| 126 |
+
print(event.model_dump())
|
| 127 |
+
'''
|
| 128 |
+
{
|
| 129 |
+
'event_datetime': {
|
| 130 |
+
'start': datetime.datetime(
|
| 131 |
+
2024, 1, 1, 15, 0, tzinfo=datetime.timezone.utc
|
| 132 |
+
),
|
| 133 |
+
'end': datetime.datetime(
|
| 134 |
+
2024, 1, 3, 14, 0, tzinfo=datetime.timezone.utc
|
| 135 |
+
),
|
| 136 |
+
}
|
| 137 |
+
}
|
| 138 |
+
'''
|
| 139 |
+
|
| 140 |
+
print(event.model_dump_json())
|
| 141 |
+
'''
|
| 142 |
+
{"event_datetime":{"start":"2024-01-01T15:00:00Z","end":"2024-01-03T14:00:00Z"}}
|
| 143 |
+
'''
|
| 144 |
+
```
|
| 145 |
+
|
| 146 |
+
Attributes:
|
| 147 |
+
func: The serializer function to be wrapped.
|
| 148 |
+
return_type: The return type for the function. If omitted it will be inferred from the type annotation.
|
| 149 |
+
when_used: Determines when this serializer should be used. Accepts a string with values `'always'`,
|
| 150 |
+
`'unless-none'`, `'json'`, and `'json-unless-none'`. Defaults to 'always'.
|
| 151 |
+
"""
|
| 152 |
+
|
| 153 |
+
func: core_schema.WrapSerializerFunction
|
| 154 |
+
return_type: Any = PydanticUndefined
|
| 155 |
+
when_used: WhenUsed = 'always'
|
| 156 |
+
|
| 157 |
+
def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
|
| 158 |
+
"""This method is used to get the Pydantic core schema of the class.
|
| 159 |
+
|
| 160 |
+
Args:
|
| 161 |
+
source_type: Source type.
|
| 162 |
+
handler: Core schema handler.
|
| 163 |
+
|
| 164 |
+
Returns:
|
| 165 |
+
The generated core schema of the class.
|
| 166 |
+
"""
|
| 167 |
+
schema = handler(source_type)
|
| 168 |
+
globalns, localns = handler._get_types_namespace()
|
| 169 |
+
try:
|
| 170 |
+
# Do not pass in globals as the function could be defined in a different module.
|
| 171 |
+
# Instead, let `get_function_return_type` infer the globals to use, but still pass
|
| 172 |
+
# in locals that may contain a parent/rebuild namespace:
|
| 173 |
+
return_type = _decorators.get_function_return_type(
|
| 174 |
+
self.func,
|
| 175 |
+
self.return_type,
|
| 176 |
+
localns=handler._get_types_namespace().locals,
|
| 177 |
+
)
|
| 178 |
+
except NameError as e:
|
| 179 |
+
raise PydanticUndefinedAnnotation.from_name_error(e) from e
|
| 180 |
+
return_schema = None if return_type is PydanticUndefined else handler.generate_schema(return_type)
|
| 181 |
+
schema['serialization'] = core_schema.wrap_serializer_function_ser_schema(
|
| 182 |
+
function=self.func,
|
| 183 |
+
info_arg=_decorators.inspect_annotated_serializer(self.func, 'wrap'),
|
| 184 |
+
return_schema=return_schema,
|
| 185 |
+
when_used=self.when_used,
|
| 186 |
+
)
|
| 187 |
+
return schema
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
if TYPE_CHECKING:
|
| 191 |
+
_Partial: TypeAlias = 'partial[Any] | partialmethod[Any]'
|
| 192 |
+
|
| 193 |
+
FieldPlainSerializer: TypeAlias = 'core_schema.SerializerFunction | _Partial'
|
| 194 |
+
"""A field serializer method or function in `plain` mode."""
|
| 195 |
+
|
| 196 |
+
FieldWrapSerializer: TypeAlias = 'core_schema.WrapSerializerFunction | _Partial'
|
| 197 |
+
"""A field serializer method or function in `wrap` mode."""
|
| 198 |
+
|
| 199 |
+
FieldSerializer: TypeAlias = 'FieldPlainSerializer | FieldWrapSerializer'
|
| 200 |
+
"""A field serializer method or function."""
|
| 201 |
+
|
| 202 |
+
_FieldPlainSerializerT = TypeVar('_FieldPlainSerializerT', bound=FieldPlainSerializer)
|
| 203 |
+
_FieldWrapSerializerT = TypeVar('_FieldWrapSerializerT', bound=FieldWrapSerializer)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
@overload
|
| 207 |
+
def field_serializer(
|
| 208 |
+
field: str,
|
| 209 |
+
/,
|
| 210 |
+
*fields: str,
|
| 211 |
+
mode: Literal['wrap'],
|
| 212 |
+
return_type: Any = ...,
|
| 213 |
+
when_used: WhenUsed = ...,
|
| 214 |
+
check_fields: bool | None = ...,
|
| 215 |
+
) -> Callable[[_FieldWrapSerializerT], _FieldWrapSerializerT]: ...
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
@overload
|
| 219 |
+
def field_serializer(
|
| 220 |
+
field: str,
|
| 221 |
+
/,
|
| 222 |
+
*fields: str,
|
| 223 |
+
mode: Literal['plain'] = ...,
|
| 224 |
+
return_type: Any = ...,
|
| 225 |
+
when_used: WhenUsed = ...,
|
| 226 |
+
check_fields: bool | None = ...,
|
| 227 |
+
) -> Callable[[_FieldPlainSerializerT], _FieldPlainSerializerT]: ...
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def field_serializer(
|
| 231 |
+
*fields: str,
|
| 232 |
+
mode: Literal['plain', 'wrap'] = 'plain',
|
| 233 |
+
return_type: Any = PydanticUndefined,
|
| 234 |
+
when_used: WhenUsed = 'always',
|
| 235 |
+
check_fields: bool | None = None,
|
| 236 |
+
) -> (
|
| 237 |
+
Callable[[_FieldWrapSerializerT], _FieldWrapSerializerT]
|
| 238 |
+
| Callable[[_FieldPlainSerializerT], _FieldPlainSerializerT]
|
| 239 |
+
):
|
| 240 |
+
"""Decorator that enables custom field serialization.
|
| 241 |
+
|
| 242 |
+
In the below example, a field of type `set` is used to mitigate duplication. A `field_serializer` is used to serialize the data as a sorted list.
|
| 243 |
+
|
| 244 |
+
```python
|
| 245 |
+
from typing import Set
|
| 246 |
+
|
| 247 |
+
from pydantic import BaseModel, field_serializer
|
| 248 |
+
|
| 249 |
+
class StudentModel(BaseModel):
|
| 250 |
+
name: str = 'Jane'
|
| 251 |
+
courses: Set[str]
|
| 252 |
+
|
| 253 |
+
@field_serializer('courses', when_used='json')
|
| 254 |
+
def serialize_courses_in_order(self, courses: Set[str]):
|
| 255 |
+
return sorted(courses)
|
| 256 |
+
|
| 257 |
+
student = StudentModel(courses={'Math', 'Chemistry', 'English'})
|
| 258 |
+
print(student.model_dump_json())
|
| 259 |
+
#> {"name":"Jane","courses":["Chemistry","English","Math"]}
|
| 260 |
+
```
|
| 261 |
+
|
| 262 |
+
See [Custom serializers](../concepts/serialization.md#custom-serializers) for more information.
|
| 263 |
+
|
| 264 |
+
Four signatures are supported:
|
| 265 |
+
|
| 266 |
+
- `(self, value: Any, info: FieldSerializationInfo)`
|
| 267 |
+
- `(self, value: Any, nxt: SerializerFunctionWrapHandler, info: FieldSerializationInfo)`
|
| 268 |
+
- `(value: Any, info: SerializationInfo)`
|
| 269 |
+
- `(value: Any, nxt: SerializerFunctionWrapHandler, info: SerializationInfo)`
|
| 270 |
+
|
| 271 |
+
Args:
|
| 272 |
+
fields: Which field(s) the method should be called on.
|
| 273 |
+
mode: The serialization mode.
|
| 274 |
+
|
| 275 |
+
- `plain` means the function will be called instead of the default serialization logic,
|
| 276 |
+
- `wrap` means the function will be called with an argument to optionally call the
|
| 277 |
+
default serialization logic.
|
| 278 |
+
return_type: Optional return type for the function, if omitted it will be inferred from the type annotation.
|
| 279 |
+
when_used: Determines the serializer will be used for serialization.
|
| 280 |
+
check_fields: Whether to check that the fields actually exist on the model.
|
| 281 |
+
|
| 282 |
+
Returns:
|
| 283 |
+
The decorator function.
|
| 284 |
+
"""
|
| 285 |
+
|
| 286 |
+
def dec(f: FieldSerializer) -> _decorators.PydanticDescriptorProxy[Any]:
|
| 287 |
+
dec_info = _decorators.FieldSerializerDecoratorInfo(
|
| 288 |
+
fields=fields,
|
| 289 |
+
mode=mode,
|
| 290 |
+
return_type=return_type,
|
| 291 |
+
when_used=when_used,
|
| 292 |
+
check_fields=check_fields,
|
| 293 |
+
)
|
| 294 |
+
return _decorators.PydanticDescriptorProxy(f, dec_info) # pyright: ignore[reportArgumentType]
|
| 295 |
+
|
| 296 |
+
return dec # pyright: ignore[reportReturnType]
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
if TYPE_CHECKING:
|
| 300 |
+
# The first argument in the following callables represent the `self` type:
|
| 301 |
+
|
| 302 |
+
ModelPlainSerializerWithInfo: TypeAlias = Callable[[Any, SerializationInfo], Any]
|
| 303 |
+
"""A model serializer method with the `info` argument, in `plain` mode."""
|
| 304 |
+
|
| 305 |
+
ModelPlainSerializerWithoutInfo: TypeAlias = Callable[[Any], Any]
|
| 306 |
+
"""A model serializer method without the `info` argument, in `plain` mode."""
|
| 307 |
+
|
| 308 |
+
ModelPlainSerializer: TypeAlias = 'ModelPlainSerializerWithInfo | ModelPlainSerializerWithoutInfo'
|
| 309 |
+
"""A model serializer method in `plain` mode."""
|
| 310 |
+
|
| 311 |
+
ModelWrapSerializerWithInfo: TypeAlias = Callable[[Any, SerializerFunctionWrapHandler, SerializationInfo], Any]
|
| 312 |
+
"""A model serializer method with the `info` argument, in `wrap` mode."""
|
| 313 |
+
|
| 314 |
+
ModelWrapSerializerWithoutInfo: TypeAlias = Callable[[Any, SerializerFunctionWrapHandler], Any]
|
| 315 |
+
"""A model serializer method without the `info` argument, in `wrap` mode."""
|
| 316 |
+
|
| 317 |
+
ModelWrapSerializer: TypeAlias = 'ModelWrapSerializerWithInfo | ModelWrapSerializerWithoutInfo'
|
| 318 |
+
"""A model serializer method in `wrap` mode."""
|
| 319 |
+
|
| 320 |
+
ModelSerializer: TypeAlias = 'ModelPlainSerializer | ModelWrapSerializer'
|
| 321 |
+
|
| 322 |
+
_ModelPlainSerializerT = TypeVar('_ModelPlainSerializerT', bound=ModelPlainSerializer)
|
| 323 |
+
_ModelWrapSerializerT = TypeVar('_ModelWrapSerializerT', bound=ModelWrapSerializer)
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
@overload
|
| 327 |
+
def model_serializer(f: _ModelPlainSerializerT, /) -> _ModelPlainSerializerT: ...
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
@overload
|
| 331 |
+
def model_serializer(
|
| 332 |
+
*, mode: Literal['wrap'], when_used: WhenUsed = 'always', return_type: Any = ...
|
| 333 |
+
) -> Callable[[_ModelWrapSerializerT], _ModelWrapSerializerT]: ...
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
@overload
|
| 337 |
+
def model_serializer(
|
| 338 |
+
*,
|
| 339 |
+
mode: Literal['plain'] = ...,
|
| 340 |
+
when_used: WhenUsed = 'always',
|
| 341 |
+
return_type: Any = ...,
|
| 342 |
+
) -> Callable[[_ModelPlainSerializerT], _ModelPlainSerializerT]: ...
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def model_serializer(
|
| 346 |
+
f: _ModelPlainSerializerT | _ModelWrapSerializerT | None = None,
|
| 347 |
+
/,
|
| 348 |
+
*,
|
| 349 |
+
mode: Literal['plain', 'wrap'] = 'plain',
|
| 350 |
+
when_used: WhenUsed = 'always',
|
| 351 |
+
return_type: Any = PydanticUndefined,
|
| 352 |
+
) -> (
|
| 353 |
+
_ModelPlainSerializerT
|
| 354 |
+
| Callable[[_ModelWrapSerializerT], _ModelWrapSerializerT]
|
| 355 |
+
| Callable[[_ModelPlainSerializerT], _ModelPlainSerializerT]
|
| 356 |
+
):
|
| 357 |
+
"""Decorator that enables custom model serialization.
|
| 358 |
+
|
| 359 |
+
This is useful when a model need to be serialized in a customized manner, allowing for flexibility beyond just specific fields.
|
| 360 |
+
|
| 361 |
+
An example would be to serialize temperature to the same temperature scale, such as degrees Celsius.
|
| 362 |
+
|
| 363 |
+
```python
|
| 364 |
+
from typing import Literal
|
| 365 |
+
|
| 366 |
+
from pydantic import BaseModel, model_serializer
|
| 367 |
+
|
| 368 |
+
class TemperatureModel(BaseModel):
|
| 369 |
+
unit: Literal['C', 'F']
|
| 370 |
+
value: int
|
| 371 |
+
|
| 372 |
+
@model_serializer()
|
| 373 |
+
def serialize_model(self):
|
| 374 |
+
if self.unit == 'F':
|
| 375 |
+
return {'unit': 'C', 'value': int((self.value - 32) / 1.8)}
|
| 376 |
+
return {'unit': self.unit, 'value': self.value}
|
| 377 |
+
|
| 378 |
+
temperature = TemperatureModel(unit='F', value=212)
|
| 379 |
+
print(temperature.model_dump())
|
| 380 |
+
#> {'unit': 'C', 'value': 100}
|
| 381 |
+
```
|
| 382 |
+
|
| 383 |
+
Two signatures are supported for `mode='plain'`, which is the default:
|
| 384 |
+
|
| 385 |
+
- `(self)`
|
| 386 |
+
- `(self, info: SerializationInfo)`
|
| 387 |
+
|
| 388 |
+
And two other signatures for `mode='wrap'`:
|
| 389 |
+
|
| 390 |
+
- `(self, nxt: SerializerFunctionWrapHandler)`
|
| 391 |
+
- `(self, nxt: SerializerFunctionWrapHandler, info: SerializationInfo)`
|
| 392 |
+
|
| 393 |
+
See [Custom serializers](../concepts/serialization.md#custom-serializers) for more information.
|
| 394 |
+
|
| 395 |
+
Args:
|
| 396 |
+
f: The function to be decorated.
|
| 397 |
+
mode: The serialization mode.
|
| 398 |
+
|
| 399 |
+
- `'plain'` means the function will be called instead of the default serialization logic
|
| 400 |
+
- `'wrap'` means the function will be called with an argument to optionally call the default
|
| 401 |
+
serialization logic.
|
| 402 |
+
when_used: Determines when this serializer should be used.
|
| 403 |
+
return_type: The return type for the function. If omitted it will be inferred from the type annotation.
|
| 404 |
+
|
| 405 |
+
Returns:
|
| 406 |
+
The decorator function.
|
| 407 |
+
"""
|
| 408 |
+
|
| 409 |
+
def dec(f: ModelSerializer) -> _decorators.PydanticDescriptorProxy[Any]:
|
| 410 |
+
dec_info = _decorators.ModelSerializerDecoratorInfo(mode=mode, return_type=return_type, when_used=when_used)
|
| 411 |
+
return _decorators.PydanticDescriptorProxy(f, dec_info)
|
| 412 |
+
|
| 413 |
+
if f is None:
|
| 414 |
+
return dec # pyright: ignore[reportReturnType]
|
| 415 |
+
else:
|
| 416 |
+
return dec(f) # pyright: ignore[reportReturnType]
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
AnyType = TypeVar('AnyType')
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
if TYPE_CHECKING:
|
| 423 |
+
SerializeAsAny = Annotated[AnyType, ...] # SerializeAsAny[list[str]] will be treated by type checkers as list[str]
|
| 424 |
+
"""Force serialization to ignore whatever is defined in the schema and instead ask the object
|
| 425 |
+
itself how it should be serialized.
|
| 426 |
+
In particular, this means that when model subclasses are serialized, fields present in the subclass
|
| 427 |
+
but not in the original schema will be included.
|
| 428 |
+
"""
|
| 429 |
+
else:
|
| 430 |
+
|
| 431 |
+
@dataclasses.dataclass(**_internal_dataclass.slots_true)
|
| 432 |
+
class SerializeAsAny: # noqa: D101
|
| 433 |
+
def __class_getitem__(cls, item: Any) -> Any:
|
| 434 |
+
return Annotated[item, SerializeAsAny()]
|
| 435 |
+
|
| 436 |
+
def __get_pydantic_core_schema__(
|
| 437 |
+
self, source_type: Any, handler: GetCoreSchemaHandler
|
| 438 |
+
) -> core_schema.CoreSchema:
|
| 439 |
+
schema = handler(source_type)
|
| 440 |
+
schema_to_update = schema
|
| 441 |
+
while schema_to_update['type'] == 'definitions':
|
| 442 |
+
schema_to_update = schema_to_update.copy()
|
| 443 |
+
schema_to_update = schema_to_update['schema']
|
| 444 |
+
schema_to_update['serialization'] = core_schema.wrap_serializer_function_ser_schema(
|
| 445 |
+
lambda x, h: h(x), schema=core_schema.any_schema()
|
| 446 |
+
)
|
| 447 |
+
return schema
|
| 448 |
+
|
| 449 |
+
__hash__ = object.__hash__
|
vllm/lib/python3.10/site-packages/pydantic/functional_validators.py
ADDED
|
@@ -0,0 +1,846 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""This module contains related classes and functions for validation."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations as _annotations
|
| 4 |
+
|
| 5 |
+
import dataclasses
|
| 6 |
+
import sys
|
| 7 |
+
from functools import partialmethod
|
| 8 |
+
from types import FunctionType
|
| 9 |
+
from typing import TYPE_CHECKING, Any, Callable, TypeVar, Union, cast, overload
|
| 10 |
+
|
| 11 |
+
from pydantic_core import PydanticUndefined, core_schema
|
| 12 |
+
from pydantic_core import core_schema as _core_schema
|
| 13 |
+
from typing_extensions import Annotated, Literal, Self, TypeAlias
|
| 14 |
+
|
| 15 |
+
from ._internal import _decorators, _generics, _internal_dataclass
|
| 16 |
+
from .annotated_handlers import GetCoreSchemaHandler
|
| 17 |
+
from .errors import PydanticUserError
|
| 18 |
+
|
| 19 |
+
if sys.version_info < (3, 11):
|
| 20 |
+
from typing_extensions import Protocol
|
| 21 |
+
else:
|
| 22 |
+
from typing import Protocol
|
| 23 |
+
|
| 24 |
+
_inspect_validator = _decorators.inspect_validator
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@dataclasses.dataclass(frozen=True, **_internal_dataclass.slots_true)
|
| 28 |
+
class AfterValidator:
|
| 29 |
+
"""Usage docs: https://docs.pydantic.dev/2.10/concepts/validators/#annotated-validators
|
| 30 |
+
|
| 31 |
+
A metadata class that indicates that a validation should be applied **after** the inner validation logic.
|
| 32 |
+
|
| 33 |
+
Attributes:
|
| 34 |
+
func: The validator function.
|
| 35 |
+
|
| 36 |
+
Example:
|
| 37 |
+
```python
|
| 38 |
+
from typing_extensions import Annotated
|
| 39 |
+
|
| 40 |
+
from pydantic import AfterValidator, BaseModel, ValidationError
|
| 41 |
+
|
| 42 |
+
MyInt = Annotated[int, AfterValidator(lambda v: v + 1)]
|
| 43 |
+
|
| 44 |
+
class Model(BaseModel):
|
| 45 |
+
a: MyInt
|
| 46 |
+
|
| 47 |
+
print(Model(a=1).a)
|
| 48 |
+
#> 2
|
| 49 |
+
|
| 50 |
+
try:
|
| 51 |
+
Model(a='a')
|
| 52 |
+
except ValidationError as e:
|
| 53 |
+
print(e.json(indent=2))
|
| 54 |
+
'''
|
| 55 |
+
[
|
| 56 |
+
{
|
| 57 |
+
"type": "int_parsing",
|
| 58 |
+
"loc": [
|
| 59 |
+
"a"
|
| 60 |
+
],
|
| 61 |
+
"msg": "Input should be a valid integer, unable to parse string as an integer",
|
| 62 |
+
"input": "a",
|
| 63 |
+
"url": "https://errors.pydantic.dev/2/v/int_parsing"
|
| 64 |
+
}
|
| 65 |
+
]
|
| 66 |
+
'''
|
| 67 |
+
```
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
func: core_schema.NoInfoValidatorFunction | core_schema.WithInfoValidatorFunction
|
| 71 |
+
|
| 72 |
+
def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
|
| 73 |
+
schema = handler(source_type)
|
| 74 |
+
info_arg = _inspect_validator(self.func, 'after')
|
| 75 |
+
if info_arg:
|
| 76 |
+
func = cast(core_schema.WithInfoValidatorFunction, self.func)
|
| 77 |
+
return core_schema.with_info_after_validator_function(func, schema=schema, field_name=handler.field_name)
|
| 78 |
+
else:
|
| 79 |
+
func = cast(core_schema.NoInfoValidatorFunction, self.func)
|
| 80 |
+
return core_schema.no_info_after_validator_function(func, schema=schema)
|
| 81 |
+
|
| 82 |
+
@classmethod
|
| 83 |
+
def _from_decorator(cls, decorator: _decorators.Decorator[_decorators.FieldValidatorDecoratorInfo]) -> Self:
|
| 84 |
+
return cls(func=decorator.func)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@dataclasses.dataclass(frozen=True, **_internal_dataclass.slots_true)
|
| 88 |
+
class BeforeValidator:
|
| 89 |
+
"""Usage docs: https://docs.pydantic.dev/2.10/concepts/validators/#annotated-validators
|
| 90 |
+
|
| 91 |
+
A metadata class that indicates that a validation should be applied **before** the inner validation logic.
|
| 92 |
+
|
| 93 |
+
Attributes:
|
| 94 |
+
func: The validator function.
|
| 95 |
+
json_schema_input_type: The input type of the function. This is only used to generate the appropriate
|
| 96 |
+
JSON Schema (in validation mode).
|
| 97 |
+
|
| 98 |
+
Example:
|
| 99 |
+
```python
|
| 100 |
+
from typing_extensions import Annotated
|
| 101 |
+
|
| 102 |
+
from pydantic import BaseModel, BeforeValidator
|
| 103 |
+
|
| 104 |
+
MyInt = Annotated[int, BeforeValidator(lambda v: v + 1)]
|
| 105 |
+
|
| 106 |
+
class Model(BaseModel):
|
| 107 |
+
a: MyInt
|
| 108 |
+
|
| 109 |
+
print(Model(a=1).a)
|
| 110 |
+
#> 2
|
| 111 |
+
|
| 112 |
+
try:
|
| 113 |
+
Model(a='a')
|
| 114 |
+
except TypeError as e:
|
| 115 |
+
print(e)
|
| 116 |
+
#> can only concatenate str (not "int") to str
|
| 117 |
+
```
|
| 118 |
+
"""
|
| 119 |
+
|
| 120 |
+
func: core_schema.NoInfoValidatorFunction | core_schema.WithInfoValidatorFunction
|
| 121 |
+
json_schema_input_type: Any = PydanticUndefined
|
| 122 |
+
|
| 123 |
+
def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
|
| 124 |
+
schema = handler(source_type)
|
| 125 |
+
input_schema = (
|
| 126 |
+
None
|
| 127 |
+
if self.json_schema_input_type is PydanticUndefined
|
| 128 |
+
else handler.generate_schema(self.json_schema_input_type)
|
| 129 |
+
)
|
| 130 |
+
# Try to resolve the original schema if required, because schema cleaning
|
| 131 |
+
# won't inline references in metadata:
|
| 132 |
+
if input_schema is not None:
|
| 133 |
+
try:
|
| 134 |
+
input_schema = handler.resolve_ref_schema(input_schema)
|
| 135 |
+
except LookupError:
|
| 136 |
+
pass
|
| 137 |
+
metadata = {'pydantic_js_input_core_schema': input_schema} if input_schema is not None else {}
|
| 138 |
+
|
| 139 |
+
info_arg = _inspect_validator(self.func, 'before')
|
| 140 |
+
if info_arg:
|
| 141 |
+
func = cast(core_schema.WithInfoValidatorFunction, self.func)
|
| 142 |
+
return core_schema.with_info_before_validator_function(
|
| 143 |
+
func,
|
| 144 |
+
schema=schema,
|
| 145 |
+
field_name=handler.field_name,
|
| 146 |
+
metadata=metadata,
|
| 147 |
+
)
|
| 148 |
+
else:
|
| 149 |
+
func = cast(core_schema.NoInfoValidatorFunction, self.func)
|
| 150 |
+
return core_schema.no_info_before_validator_function(func, schema=schema, metadata=metadata)
|
| 151 |
+
|
| 152 |
+
@classmethod
|
| 153 |
+
def _from_decorator(cls, decorator: _decorators.Decorator[_decorators.FieldValidatorDecoratorInfo]) -> Self:
|
| 154 |
+
return cls(
|
| 155 |
+
func=decorator.func,
|
| 156 |
+
json_schema_input_type=decorator.info.json_schema_input_type,
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
@dataclasses.dataclass(frozen=True, **_internal_dataclass.slots_true)
|
| 161 |
+
class PlainValidator:
|
| 162 |
+
"""Usage docs: https://docs.pydantic.dev/2.10/concepts/validators/#annotated-validators
|
| 163 |
+
|
| 164 |
+
A metadata class that indicates that a validation should be applied **instead** of the inner validation logic.
|
| 165 |
+
|
| 166 |
+
!!! note
|
| 167 |
+
Before v2.9, `PlainValidator` wasn't always compatible with JSON Schema generation for `mode='validation'`.
|
| 168 |
+
You can now use the `json_schema_input_type` argument to specify the input type of the function
|
| 169 |
+
to be used in the JSON schema when `mode='validation'` (the default). See the example below for more details.
|
| 170 |
+
|
| 171 |
+
Attributes:
|
| 172 |
+
func: The validator function.
|
| 173 |
+
json_schema_input_type: The input type of the function. This is only used to generate the appropriate
|
| 174 |
+
JSON Schema (in validation mode). If not provided, will default to `Any`.
|
| 175 |
+
|
| 176 |
+
Example:
|
| 177 |
+
```python
|
| 178 |
+
from typing import Union
|
| 179 |
+
|
| 180 |
+
from typing_extensions import Annotated
|
| 181 |
+
|
| 182 |
+
from pydantic import BaseModel, PlainValidator
|
| 183 |
+
|
| 184 |
+
MyInt = Annotated[
|
| 185 |
+
int,
|
| 186 |
+
PlainValidator(
|
| 187 |
+
lambda v: int(v) + 1, json_schema_input_type=Union[str, int] # (1)!
|
| 188 |
+
),
|
| 189 |
+
]
|
| 190 |
+
|
| 191 |
+
class Model(BaseModel):
|
| 192 |
+
a: MyInt
|
| 193 |
+
|
| 194 |
+
print(Model(a='1').a)
|
| 195 |
+
#> 2
|
| 196 |
+
|
| 197 |
+
print(Model(a=1).a)
|
| 198 |
+
#> 2
|
| 199 |
+
```
|
| 200 |
+
|
| 201 |
+
1. In this example, we've specified the `json_schema_input_type` as `Union[str, int]` which indicates to the JSON schema
|
| 202 |
+
generator that in validation mode, the input type for the `a` field can be either a `str` or an `int`.
|
| 203 |
+
"""
|
| 204 |
+
|
| 205 |
+
func: core_schema.NoInfoValidatorFunction | core_schema.WithInfoValidatorFunction
|
| 206 |
+
json_schema_input_type: Any = Any
|
| 207 |
+
|
| 208 |
+
def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
|
| 209 |
+
# Note that for some valid uses of PlainValidator, it is not possible to generate a core schema for the
|
| 210 |
+
# source_type, so calling `handler(source_type)` will error, which prevents us from generating a proper
|
| 211 |
+
# serialization schema. To work around this for use cases that will not involve serialization, we simply
|
| 212 |
+
# catch any PydanticSchemaGenerationError that may be raised while attempting to build the serialization schema
|
| 213 |
+
# and abort any attempts to handle special serialization.
|
| 214 |
+
from pydantic import PydanticSchemaGenerationError
|
| 215 |
+
|
| 216 |
+
try:
|
| 217 |
+
schema = handler(source_type)
|
| 218 |
+
# TODO if `schema['serialization']` is one of `'include-exclude-dict/sequence',
|
| 219 |
+
# schema validation will fail. That's why we use 'type ignore' comments below.
|
| 220 |
+
serialization = schema.get(
|
| 221 |
+
'serialization',
|
| 222 |
+
core_schema.wrap_serializer_function_ser_schema(
|
| 223 |
+
function=lambda v, h: h(v),
|
| 224 |
+
schema=schema,
|
| 225 |
+
return_schema=handler.generate_schema(source_type),
|
| 226 |
+
),
|
| 227 |
+
)
|
| 228 |
+
except PydanticSchemaGenerationError:
|
| 229 |
+
serialization = None
|
| 230 |
+
|
| 231 |
+
input_schema = handler.generate_schema(self.json_schema_input_type)
|
| 232 |
+
# Try to resolve the original schema if required, because schema cleaning
|
| 233 |
+
# won't inline references in metadata:
|
| 234 |
+
try:
|
| 235 |
+
input_schema = handler.resolve_ref_schema(input_schema)
|
| 236 |
+
except LookupError:
|
| 237 |
+
pass
|
| 238 |
+
metadata = {'pydantic_js_input_core_schema': input_schema} if input_schema is not None else {}
|
| 239 |
+
|
| 240 |
+
info_arg = _inspect_validator(self.func, 'plain')
|
| 241 |
+
if info_arg:
|
| 242 |
+
func = cast(core_schema.WithInfoValidatorFunction, self.func)
|
| 243 |
+
return core_schema.with_info_plain_validator_function(
|
| 244 |
+
func,
|
| 245 |
+
field_name=handler.field_name,
|
| 246 |
+
serialization=serialization, # pyright: ignore[reportArgumentType]
|
| 247 |
+
metadata=metadata,
|
| 248 |
+
)
|
| 249 |
+
else:
|
| 250 |
+
func = cast(core_schema.NoInfoValidatorFunction, self.func)
|
| 251 |
+
return core_schema.no_info_plain_validator_function(
|
| 252 |
+
func,
|
| 253 |
+
serialization=serialization, # pyright: ignore[reportArgumentType]
|
| 254 |
+
metadata=metadata,
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
@classmethod
|
| 258 |
+
def _from_decorator(cls, decorator: _decorators.Decorator[_decorators.FieldValidatorDecoratorInfo]) -> Self:
|
| 259 |
+
return cls(
|
| 260 |
+
func=decorator.func,
|
| 261 |
+
json_schema_input_type=decorator.info.json_schema_input_type,
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@dataclasses.dataclass(frozen=True, **_internal_dataclass.slots_true)
|
| 266 |
+
class WrapValidator:
|
| 267 |
+
"""Usage docs: https://docs.pydantic.dev/2.10/concepts/validators/#annotated-validators
|
| 268 |
+
|
| 269 |
+
A metadata class that indicates that a validation should be applied **around** the inner validation logic.
|
| 270 |
+
|
| 271 |
+
Attributes:
|
| 272 |
+
func: The validator function.
|
| 273 |
+
json_schema_input_type: The input type of the function. This is only used to generate the appropriate
|
| 274 |
+
JSON Schema (in validation mode).
|
| 275 |
+
|
| 276 |
+
```python
|
| 277 |
+
from datetime import datetime
|
| 278 |
+
|
| 279 |
+
from typing_extensions import Annotated
|
| 280 |
+
|
| 281 |
+
from pydantic import BaseModel, ValidationError, WrapValidator
|
| 282 |
+
|
| 283 |
+
def validate_timestamp(v, handler):
|
| 284 |
+
if v == 'now':
|
| 285 |
+
# we don't want to bother with further validation, just return the new value
|
| 286 |
+
return datetime.now()
|
| 287 |
+
try:
|
| 288 |
+
return handler(v)
|
| 289 |
+
except ValidationError:
|
| 290 |
+
# validation failed, in this case we want to return a default value
|
| 291 |
+
return datetime(2000, 1, 1)
|
| 292 |
+
|
| 293 |
+
MyTimestamp = Annotated[datetime, WrapValidator(validate_timestamp)]
|
| 294 |
+
|
| 295 |
+
class Model(BaseModel):
|
| 296 |
+
a: MyTimestamp
|
| 297 |
+
|
| 298 |
+
print(Model(a='now').a)
|
| 299 |
+
#> 2032-01-02 03:04:05.000006
|
| 300 |
+
print(Model(a='invalid').a)
|
| 301 |
+
#> 2000-01-01 00:00:00
|
| 302 |
+
```
|
| 303 |
+
"""
|
| 304 |
+
|
| 305 |
+
func: core_schema.NoInfoWrapValidatorFunction | core_schema.WithInfoWrapValidatorFunction
|
| 306 |
+
json_schema_input_type: Any = PydanticUndefined
|
| 307 |
+
|
| 308 |
+
def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
|
| 309 |
+
schema = handler(source_type)
|
| 310 |
+
input_schema = (
|
| 311 |
+
None
|
| 312 |
+
if self.json_schema_input_type is PydanticUndefined
|
| 313 |
+
else handler.generate_schema(self.json_schema_input_type)
|
| 314 |
+
)
|
| 315 |
+
# Try to resolve the original schema if required, because schema cleaning
|
| 316 |
+
# won't inline references in metadata:
|
| 317 |
+
if input_schema is not None:
|
| 318 |
+
try:
|
| 319 |
+
input_schema = handler.resolve_ref_schema(input_schema)
|
| 320 |
+
except LookupError:
|
| 321 |
+
pass
|
| 322 |
+
metadata = {'pydantic_js_input_core_schema': input_schema} if input_schema is not None else {}
|
| 323 |
+
|
| 324 |
+
info_arg = _inspect_validator(self.func, 'wrap')
|
| 325 |
+
if info_arg:
|
| 326 |
+
func = cast(core_schema.WithInfoWrapValidatorFunction, self.func)
|
| 327 |
+
return core_schema.with_info_wrap_validator_function(
|
| 328 |
+
func,
|
| 329 |
+
schema=schema,
|
| 330 |
+
field_name=handler.field_name,
|
| 331 |
+
metadata=metadata,
|
| 332 |
+
)
|
| 333 |
+
else:
|
| 334 |
+
func = cast(core_schema.NoInfoWrapValidatorFunction, self.func)
|
| 335 |
+
return core_schema.no_info_wrap_validator_function(
|
| 336 |
+
func,
|
| 337 |
+
schema=schema,
|
| 338 |
+
metadata=metadata,
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
@classmethod
|
| 342 |
+
def _from_decorator(cls, decorator: _decorators.Decorator[_decorators.FieldValidatorDecoratorInfo]) -> Self:
|
| 343 |
+
return cls(
|
| 344 |
+
func=decorator.func,
|
| 345 |
+
json_schema_input_type=decorator.info.json_schema_input_type,
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
if TYPE_CHECKING:
|
| 350 |
+
|
| 351 |
+
class _OnlyValueValidatorClsMethod(Protocol):
|
| 352 |
+
def __call__(self, cls: Any, value: Any, /) -> Any: ...
|
| 353 |
+
|
| 354 |
+
class _V2ValidatorClsMethod(Protocol):
|
| 355 |
+
def __call__(self, cls: Any, value: Any, info: _core_schema.ValidationInfo, /) -> Any: ...
|
| 356 |
+
|
| 357 |
+
class _OnlyValueWrapValidatorClsMethod(Protocol):
|
| 358 |
+
def __call__(self, cls: Any, value: Any, handler: _core_schema.ValidatorFunctionWrapHandler, /) -> Any: ...
|
| 359 |
+
|
| 360 |
+
class _V2WrapValidatorClsMethod(Protocol):
|
| 361 |
+
def __call__(
|
| 362 |
+
self,
|
| 363 |
+
cls: Any,
|
| 364 |
+
value: Any,
|
| 365 |
+
handler: _core_schema.ValidatorFunctionWrapHandler,
|
| 366 |
+
info: _core_schema.ValidationInfo,
|
| 367 |
+
/,
|
| 368 |
+
) -> Any: ...
|
| 369 |
+
|
| 370 |
+
_V2Validator = Union[
|
| 371 |
+
_V2ValidatorClsMethod,
|
| 372 |
+
_core_schema.WithInfoValidatorFunction,
|
| 373 |
+
_OnlyValueValidatorClsMethod,
|
| 374 |
+
_core_schema.NoInfoValidatorFunction,
|
| 375 |
+
]
|
| 376 |
+
|
| 377 |
+
_V2WrapValidator = Union[
|
| 378 |
+
_V2WrapValidatorClsMethod,
|
| 379 |
+
_core_schema.WithInfoWrapValidatorFunction,
|
| 380 |
+
_OnlyValueWrapValidatorClsMethod,
|
| 381 |
+
_core_schema.NoInfoWrapValidatorFunction,
|
| 382 |
+
]
|
| 383 |
+
|
| 384 |
+
_PartialClsOrStaticMethod: TypeAlias = Union[classmethod[Any, Any, Any], staticmethod[Any, Any], partialmethod[Any]]
|
| 385 |
+
|
| 386 |
+
_V2BeforeAfterOrPlainValidatorType = TypeVar(
|
| 387 |
+
'_V2BeforeAfterOrPlainValidatorType',
|
| 388 |
+
bound=Union[_V2Validator, _PartialClsOrStaticMethod],
|
| 389 |
+
)
|
| 390 |
+
_V2WrapValidatorType = TypeVar('_V2WrapValidatorType', bound=Union[_V2WrapValidator, _PartialClsOrStaticMethod])
|
| 391 |
+
|
| 392 |
+
FieldValidatorModes: TypeAlias = Literal['before', 'after', 'wrap', 'plain']
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
@overload
|
| 396 |
+
def field_validator(
|
| 397 |
+
field: str,
|
| 398 |
+
/,
|
| 399 |
+
*fields: str,
|
| 400 |
+
mode: Literal['wrap'],
|
| 401 |
+
check_fields: bool | None = ...,
|
| 402 |
+
json_schema_input_type: Any = ...,
|
| 403 |
+
) -> Callable[[_V2WrapValidatorType], _V2WrapValidatorType]: ...
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
@overload
|
| 407 |
+
def field_validator(
|
| 408 |
+
field: str,
|
| 409 |
+
/,
|
| 410 |
+
*fields: str,
|
| 411 |
+
mode: Literal['before', 'plain'],
|
| 412 |
+
check_fields: bool | None = ...,
|
| 413 |
+
json_schema_input_type: Any = ...,
|
| 414 |
+
) -> Callable[[_V2BeforeAfterOrPlainValidatorType], _V2BeforeAfterOrPlainValidatorType]: ...
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
@overload
|
| 418 |
+
def field_validator(
|
| 419 |
+
field: str,
|
| 420 |
+
/,
|
| 421 |
+
*fields: str,
|
| 422 |
+
mode: Literal['after'] = ...,
|
| 423 |
+
check_fields: bool | None = ...,
|
| 424 |
+
) -> Callable[[_V2BeforeAfterOrPlainValidatorType], _V2BeforeAfterOrPlainValidatorType]: ...
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def field_validator(
|
| 428 |
+
field: str,
|
| 429 |
+
/,
|
| 430 |
+
*fields: str,
|
| 431 |
+
mode: FieldValidatorModes = 'after',
|
| 432 |
+
check_fields: bool | None = None,
|
| 433 |
+
json_schema_input_type: Any = PydanticUndefined,
|
| 434 |
+
) -> Callable[[Any], Any]:
|
| 435 |
+
"""Usage docs: https://docs.pydantic.dev/2.10/concepts/validators/#field-validators
|
| 436 |
+
|
| 437 |
+
Decorate methods on the class indicating that they should be used to validate fields.
|
| 438 |
+
|
| 439 |
+
Example usage:
|
| 440 |
+
```python
|
| 441 |
+
from typing import Any
|
| 442 |
+
|
| 443 |
+
from pydantic import (
|
| 444 |
+
BaseModel,
|
| 445 |
+
ValidationError,
|
| 446 |
+
field_validator,
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
class Model(BaseModel):
|
| 450 |
+
a: str
|
| 451 |
+
|
| 452 |
+
@field_validator('a')
|
| 453 |
+
@classmethod
|
| 454 |
+
def ensure_foobar(cls, v: Any):
|
| 455 |
+
if 'foobar' not in v:
|
| 456 |
+
raise ValueError('"foobar" not found in a')
|
| 457 |
+
return v
|
| 458 |
+
|
| 459 |
+
print(repr(Model(a='this is foobar good')))
|
| 460 |
+
#> Model(a='this is foobar good')
|
| 461 |
+
|
| 462 |
+
try:
|
| 463 |
+
Model(a='snap')
|
| 464 |
+
except ValidationError as exc_info:
|
| 465 |
+
print(exc_info)
|
| 466 |
+
'''
|
| 467 |
+
1 validation error for Model
|
| 468 |
+
a
|
| 469 |
+
Value error, "foobar" not found in a [type=value_error, input_value='snap', input_type=str]
|
| 470 |
+
'''
|
| 471 |
+
```
|
| 472 |
+
|
| 473 |
+
For more in depth examples, see [Field Validators](../concepts/validators.md#field-validators).
|
| 474 |
+
|
| 475 |
+
Args:
|
| 476 |
+
field: The first field the `field_validator` should be called on; this is separate
|
| 477 |
+
from `fields` to ensure an error is raised if you don't pass at least one.
|
| 478 |
+
*fields: Additional field(s) the `field_validator` should be called on.
|
| 479 |
+
mode: Specifies whether to validate the fields before or after validation.
|
| 480 |
+
check_fields: Whether to check that the fields actually exist on the model.
|
| 481 |
+
json_schema_input_type: The input type of the function. This is only used to generate
|
| 482 |
+
the appropriate JSON Schema (in validation mode) and can only specified
|
| 483 |
+
when `mode` is either `'before'`, `'plain'` or `'wrap'`.
|
| 484 |
+
|
| 485 |
+
Returns:
|
| 486 |
+
A decorator that can be used to decorate a function to be used as a field_validator.
|
| 487 |
+
|
| 488 |
+
Raises:
|
| 489 |
+
PydanticUserError:
|
| 490 |
+
- If `@field_validator` is used bare (with no fields).
|
| 491 |
+
- If the args passed to `@field_validator` as fields are not strings.
|
| 492 |
+
- If `@field_validator` applied to instance methods.
|
| 493 |
+
"""
|
| 494 |
+
if isinstance(field, FunctionType):
|
| 495 |
+
raise PydanticUserError(
|
| 496 |
+
'`@field_validator` should be used with fields and keyword arguments, not bare. '
|
| 497 |
+
"E.g. usage should be `@validator('<field_name>', ...)`",
|
| 498 |
+
code='validator-no-fields',
|
| 499 |
+
)
|
| 500 |
+
|
| 501 |
+
if mode not in ('before', 'plain', 'wrap') and json_schema_input_type is not PydanticUndefined:
|
| 502 |
+
raise PydanticUserError(
|
| 503 |
+
f"`json_schema_input_type` can't be used when mode is set to {mode!r}",
|
| 504 |
+
code='validator-input-type',
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
if json_schema_input_type is PydanticUndefined and mode == 'plain':
|
| 508 |
+
json_schema_input_type = Any
|
| 509 |
+
|
| 510 |
+
fields = field, *fields
|
| 511 |
+
if not all(isinstance(field, str) for field in fields):
|
| 512 |
+
raise PydanticUserError(
|
| 513 |
+
'`@field_validator` fields should be passed as separate string args. '
|
| 514 |
+
"E.g. usage should be `@validator('<field_name_1>', '<field_name_2>', ...)`",
|
| 515 |
+
code='validator-invalid-fields',
|
| 516 |
+
)
|
| 517 |
+
|
| 518 |
+
def dec(
|
| 519 |
+
f: Callable[..., Any] | staticmethod[Any, Any] | classmethod[Any, Any, Any],
|
| 520 |
+
) -> _decorators.PydanticDescriptorProxy[Any]:
|
| 521 |
+
if _decorators.is_instance_method_from_sig(f):
|
| 522 |
+
raise PydanticUserError(
|
| 523 |
+
'`@field_validator` cannot be applied to instance methods', code='validator-instance-method'
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
# auto apply the @classmethod decorator
|
| 527 |
+
f = _decorators.ensure_classmethod_based_on_signature(f)
|
| 528 |
+
|
| 529 |
+
dec_info = _decorators.FieldValidatorDecoratorInfo(
|
| 530 |
+
fields=fields, mode=mode, check_fields=check_fields, json_schema_input_type=json_schema_input_type
|
| 531 |
+
)
|
| 532 |
+
return _decorators.PydanticDescriptorProxy(f, dec_info)
|
| 533 |
+
|
| 534 |
+
return dec
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
_ModelType = TypeVar('_ModelType')
|
| 538 |
+
_ModelTypeCo = TypeVar('_ModelTypeCo', covariant=True)
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
class ModelWrapValidatorHandler(_core_schema.ValidatorFunctionWrapHandler, Protocol[_ModelTypeCo]):
|
| 542 |
+
"""`@model_validator` decorated function handler argument type. This is used when `mode='wrap'`."""
|
| 543 |
+
|
| 544 |
+
def __call__( # noqa: D102
|
| 545 |
+
self,
|
| 546 |
+
value: Any,
|
| 547 |
+
outer_location: str | int | None = None,
|
| 548 |
+
/,
|
| 549 |
+
) -> _ModelTypeCo: # pragma: no cover
|
| 550 |
+
...
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
class ModelWrapValidatorWithoutInfo(Protocol[_ModelType]):
|
| 554 |
+
"""A `@model_validator` decorated function signature.
|
| 555 |
+
This is used when `mode='wrap'` and the function does not have info argument.
|
| 556 |
+
"""
|
| 557 |
+
|
| 558 |
+
def __call__( # noqa: D102
|
| 559 |
+
self,
|
| 560 |
+
cls: type[_ModelType],
|
| 561 |
+
# this can be a dict, a model instance
|
| 562 |
+
# or anything else that gets passed to validate_python
|
| 563 |
+
# thus validators _must_ handle all cases
|
| 564 |
+
value: Any,
|
| 565 |
+
handler: ModelWrapValidatorHandler[_ModelType],
|
| 566 |
+
/,
|
| 567 |
+
) -> _ModelType: ...
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
class ModelWrapValidator(Protocol[_ModelType]):
|
| 571 |
+
"""A `@model_validator` decorated function signature. This is used when `mode='wrap'`."""
|
| 572 |
+
|
| 573 |
+
def __call__( # noqa: D102
|
| 574 |
+
self,
|
| 575 |
+
cls: type[_ModelType],
|
| 576 |
+
# this can be a dict, a model instance
|
| 577 |
+
# or anything else that gets passed to validate_python
|
| 578 |
+
# thus validators _must_ handle all cases
|
| 579 |
+
value: Any,
|
| 580 |
+
handler: ModelWrapValidatorHandler[_ModelType],
|
| 581 |
+
info: _core_schema.ValidationInfo,
|
| 582 |
+
/,
|
| 583 |
+
) -> _ModelType: ...
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
class FreeModelBeforeValidatorWithoutInfo(Protocol):
|
| 587 |
+
"""A `@model_validator` decorated function signature.
|
| 588 |
+
This is used when `mode='before'` and the function does not have info argument.
|
| 589 |
+
"""
|
| 590 |
+
|
| 591 |
+
def __call__( # noqa: D102
|
| 592 |
+
self,
|
| 593 |
+
# this can be a dict, a model instance
|
| 594 |
+
# or anything else that gets passed to validate_python
|
| 595 |
+
# thus validators _must_ handle all cases
|
| 596 |
+
value: Any,
|
| 597 |
+
/,
|
| 598 |
+
) -> Any: ...
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
class ModelBeforeValidatorWithoutInfo(Protocol):
|
| 602 |
+
"""A `@model_validator` decorated function signature.
|
| 603 |
+
This is used when `mode='before'` and the function does not have info argument.
|
| 604 |
+
"""
|
| 605 |
+
|
| 606 |
+
def __call__( # noqa: D102
|
| 607 |
+
self,
|
| 608 |
+
cls: Any,
|
| 609 |
+
# this can be a dict, a model instance
|
| 610 |
+
# or anything else that gets passed to validate_python
|
| 611 |
+
# thus validators _must_ handle all cases
|
| 612 |
+
value: Any,
|
| 613 |
+
/,
|
| 614 |
+
) -> Any: ...
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
class FreeModelBeforeValidator(Protocol):
|
| 618 |
+
"""A `@model_validator` decorated function signature. This is used when `mode='before'`."""
|
| 619 |
+
|
| 620 |
+
def __call__( # noqa: D102
|
| 621 |
+
self,
|
| 622 |
+
# this can be a dict, a model instance
|
| 623 |
+
# or anything else that gets passed to validate_python
|
| 624 |
+
# thus validators _must_ handle all cases
|
| 625 |
+
value: Any,
|
| 626 |
+
info: _core_schema.ValidationInfo,
|
| 627 |
+
/,
|
| 628 |
+
) -> Any: ...
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
class ModelBeforeValidator(Protocol):
|
| 632 |
+
"""A `@model_validator` decorated function signature. This is used when `mode='before'`."""
|
| 633 |
+
|
| 634 |
+
def __call__( # noqa: D102
|
| 635 |
+
self,
|
| 636 |
+
cls: Any,
|
| 637 |
+
# this can be a dict, a model instance
|
| 638 |
+
# or anything else that gets passed to validate_python
|
| 639 |
+
# thus validators _must_ handle all cases
|
| 640 |
+
value: Any,
|
| 641 |
+
info: _core_schema.ValidationInfo,
|
| 642 |
+
/,
|
| 643 |
+
) -> Any: ...
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
ModelAfterValidatorWithoutInfo = Callable[[_ModelType], _ModelType]
|
| 647 |
+
"""A `@model_validator` decorated function signature. This is used when `mode='after'` and the function does not
|
| 648 |
+
have info argument.
|
| 649 |
+
"""
|
| 650 |
+
|
| 651 |
+
ModelAfterValidator = Callable[[_ModelType, _core_schema.ValidationInfo], _ModelType]
|
| 652 |
+
"""A `@model_validator` decorated function signature. This is used when `mode='after'`."""
|
| 653 |
+
|
| 654 |
+
_AnyModelWrapValidator = Union[ModelWrapValidator[_ModelType], ModelWrapValidatorWithoutInfo[_ModelType]]
|
| 655 |
+
_AnyModelBeforeValidator = Union[
|
| 656 |
+
FreeModelBeforeValidator, ModelBeforeValidator, FreeModelBeforeValidatorWithoutInfo, ModelBeforeValidatorWithoutInfo
|
| 657 |
+
]
|
| 658 |
+
_AnyModelAfterValidator = Union[ModelAfterValidator[_ModelType], ModelAfterValidatorWithoutInfo[_ModelType]]
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
@overload
|
| 662 |
+
def model_validator(
|
| 663 |
+
*,
|
| 664 |
+
mode: Literal['wrap'],
|
| 665 |
+
) -> Callable[
|
| 666 |
+
[_AnyModelWrapValidator[_ModelType]], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo]
|
| 667 |
+
]: ...
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
@overload
|
| 671 |
+
def model_validator(
|
| 672 |
+
*,
|
| 673 |
+
mode: Literal['before'],
|
| 674 |
+
) -> Callable[
|
| 675 |
+
[_AnyModelBeforeValidator], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo]
|
| 676 |
+
]: ...
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
@overload
|
| 680 |
+
def model_validator(
|
| 681 |
+
*,
|
| 682 |
+
mode: Literal['after'],
|
| 683 |
+
) -> Callable[
|
| 684 |
+
[_AnyModelAfterValidator[_ModelType]], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo]
|
| 685 |
+
]: ...
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
def model_validator(
|
| 689 |
+
*,
|
| 690 |
+
mode: Literal['wrap', 'before', 'after'],
|
| 691 |
+
) -> Any:
|
| 692 |
+
"""Usage docs: https://docs.pydantic.dev/2.10/concepts/validators/#model-validators
|
| 693 |
+
|
| 694 |
+
Decorate model methods for validation purposes.
|
| 695 |
+
|
| 696 |
+
Example usage:
|
| 697 |
+
```python
|
| 698 |
+
from typing_extensions import Self
|
| 699 |
+
|
| 700 |
+
from pydantic import BaseModel, ValidationError, model_validator
|
| 701 |
+
|
| 702 |
+
class Square(BaseModel):
|
| 703 |
+
width: float
|
| 704 |
+
height: float
|
| 705 |
+
|
| 706 |
+
@model_validator(mode='after')
|
| 707 |
+
def verify_square(self) -> Self:
|
| 708 |
+
if self.width != self.height:
|
| 709 |
+
raise ValueError('width and height do not match')
|
| 710 |
+
return self
|
| 711 |
+
|
| 712 |
+
s = Square(width=1, height=1)
|
| 713 |
+
print(repr(s))
|
| 714 |
+
#> Square(width=1.0, height=1.0)
|
| 715 |
+
|
| 716 |
+
try:
|
| 717 |
+
Square(width=1, height=2)
|
| 718 |
+
except ValidationError as e:
|
| 719 |
+
print(e)
|
| 720 |
+
'''
|
| 721 |
+
1 validation error for Square
|
| 722 |
+
Value error, width and height do not match [type=value_error, input_value={'width': 1, 'height': 2}, input_type=dict]
|
| 723 |
+
'''
|
| 724 |
+
```
|
| 725 |
+
|
| 726 |
+
For more in depth examples, see [Model Validators](../concepts/validators.md#model-validators).
|
| 727 |
+
|
| 728 |
+
Args:
|
| 729 |
+
mode: A required string literal that specifies the validation mode.
|
| 730 |
+
It can be one of the following: 'wrap', 'before', or 'after'.
|
| 731 |
+
|
| 732 |
+
Returns:
|
| 733 |
+
A decorator that can be used to decorate a function to be used as a model validator.
|
| 734 |
+
"""
|
| 735 |
+
|
| 736 |
+
def dec(f: Any) -> _decorators.PydanticDescriptorProxy[Any]:
|
| 737 |
+
# auto apply the @classmethod decorator
|
| 738 |
+
f = _decorators.ensure_classmethod_based_on_signature(f)
|
| 739 |
+
dec_info = _decorators.ModelValidatorDecoratorInfo(mode=mode)
|
| 740 |
+
return _decorators.PydanticDescriptorProxy(f, dec_info)
|
| 741 |
+
|
| 742 |
+
return dec
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
AnyType = TypeVar('AnyType')
|
| 746 |
+
|
| 747 |
+
|
| 748 |
+
if TYPE_CHECKING:
|
| 749 |
+
# If we add configurable attributes to IsInstance, we'd probably need to stop hiding it from type checkers like this
|
| 750 |
+
InstanceOf = Annotated[AnyType, ...] # `IsInstance[Sequence]` will be recognized by type checkers as `Sequence`
|
| 751 |
+
|
| 752 |
+
else:
|
| 753 |
+
|
| 754 |
+
@dataclasses.dataclass(**_internal_dataclass.slots_true)
|
| 755 |
+
class InstanceOf:
|
| 756 |
+
'''Generic type for annotating a type that is an instance of a given class.
|
| 757 |
+
|
| 758 |
+
Example:
|
| 759 |
+
```python
|
| 760 |
+
from pydantic import BaseModel, InstanceOf
|
| 761 |
+
|
| 762 |
+
class Foo:
|
| 763 |
+
...
|
| 764 |
+
|
| 765 |
+
class Bar(BaseModel):
|
| 766 |
+
foo: InstanceOf[Foo]
|
| 767 |
+
|
| 768 |
+
Bar(foo=Foo())
|
| 769 |
+
try:
|
| 770 |
+
Bar(foo=42)
|
| 771 |
+
except ValidationError as e:
|
| 772 |
+
print(e)
|
| 773 |
+
"""
|
| 774 |
+
[
|
| 775 |
+
│ {
|
| 776 |
+
│ │ 'type': 'is_instance_of',
|
| 777 |
+
│ │ 'loc': ('foo',),
|
| 778 |
+
│ │ 'msg': 'Input should be an instance of Foo',
|
| 779 |
+
│ │ 'input': 42,
|
| 780 |
+
│ │ 'ctx': {'class': 'Foo'},
|
| 781 |
+
│ │ 'url': 'https://errors.pydantic.dev/0.38.0/v/is_instance_of'
|
| 782 |
+
│ }
|
| 783 |
+
]
|
| 784 |
+
"""
|
| 785 |
+
```
|
| 786 |
+
'''
|
| 787 |
+
|
| 788 |
+
@classmethod
|
| 789 |
+
def __class_getitem__(cls, item: AnyType) -> AnyType:
|
| 790 |
+
return Annotated[item, cls()]
|
| 791 |
+
|
| 792 |
+
@classmethod
|
| 793 |
+
def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
|
| 794 |
+
from pydantic import PydanticSchemaGenerationError
|
| 795 |
+
|
| 796 |
+
# use the generic _origin_ as the second argument to isinstance when appropriate
|
| 797 |
+
instance_of_schema = core_schema.is_instance_schema(_generics.get_origin(source) or source)
|
| 798 |
+
|
| 799 |
+
try:
|
| 800 |
+
# Try to generate the "standard" schema, which will be used when loading from JSON
|
| 801 |
+
original_schema = handler(source)
|
| 802 |
+
except PydanticSchemaGenerationError:
|
| 803 |
+
# If that fails, just produce a schema that can validate from python
|
| 804 |
+
return instance_of_schema
|
| 805 |
+
else:
|
| 806 |
+
# Use the "original" approach to serialization
|
| 807 |
+
instance_of_schema['serialization'] = core_schema.wrap_serializer_function_ser_schema(
|
| 808 |
+
function=lambda v, h: h(v), schema=original_schema
|
| 809 |
+
)
|
| 810 |
+
return core_schema.json_or_python_schema(python_schema=instance_of_schema, json_schema=original_schema)
|
| 811 |
+
|
| 812 |
+
__hash__ = object.__hash__
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
if TYPE_CHECKING:
|
| 816 |
+
SkipValidation = Annotated[AnyType, ...] # SkipValidation[list[str]] will be treated by type checkers as list[str]
|
| 817 |
+
else:
|
| 818 |
+
|
| 819 |
+
@dataclasses.dataclass(**_internal_dataclass.slots_true)
|
| 820 |
+
class SkipValidation:
|
| 821 |
+
"""If this is applied as an annotation (e.g., via `x: Annotated[int, SkipValidation]`), validation will be
|
| 822 |
+
skipped. You can also use `SkipValidation[int]` as a shorthand for `Annotated[int, SkipValidation]`.
|
| 823 |
+
|
| 824 |
+
This can be useful if you want to use a type annotation for documentation/IDE/type-checking purposes,
|
| 825 |
+
and know that it is safe to skip validation for one or more of the fields.
|
| 826 |
+
|
| 827 |
+
Because this converts the validation schema to `any_schema`, subsequent annotation-applied transformations
|
| 828 |
+
may not have the expected effects. Therefore, when used, this annotation should generally be the final
|
| 829 |
+
annotation applied to a type.
|
| 830 |
+
"""
|
| 831 |
+
|
| 832 |
+
def __class_getitem__(cls, item: Any) -> Any:
|
| 833 |
+
return Annotated[item, SkipValidation()]
|
| 834 |
+
|
| 835 |
+
@classmethod
|
| 836 |
+
def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
|
| 837 |
+
original_schema = handler(source)
|
| 838 |
+
metadata = {'pydantic_js_annotation_functions': [lambda _c, h: h(original_schema)]}
|
| 839 |
+
return core_schema.any_schema(
|
| 840 |
+
metadata=metadata,
|
| 841 |
+
serialization=core_schema.wrap_serializer_function_ser_schema(
|
| 842 |
+
function=lambda v, h: h(v), schema=original_schema
|
| 843 |
+
),
|
| 844 |
+
)
|
| 845 |
+
|
| 846 |
+
__hash__ = object.__hash__
|
vllm/lib/python3.10/site-packages/pydantic/generics.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The `generics` module is a backport module from V1."""
|
| 2 |
+
|
| 3 |
+
from ._migration import getattr_migration
|
| 4 |
+
|
| 5 |
+
__getattr__ = getattr_migration(__name__)
|
vllm/lib/python3.10/site-packages/pydantic/json.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The `json` module is a backport module from V1."""
|
| 2 |
+
|
| 3 |
+
from ._migration import getattr_migration
|
| 4 |
+
|
| 5 |
+
__getattr__ = getattr_migration(__name__)
|
vllm/lib/python3.10/site-packages/pydantic/json_schema.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
vllm/lib/python3.10/site-packages/pydantic/main.py
ADDED
|
@@ -0,0 +1,1689 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Logic for creating models."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations as _annotations
|
| 4 |
+
|
| 5 |
+
import operator
|
| 6 |
+
import sys
|
| 7 |
+
import types
|
| 8 |
+
import typing
|
| 9 |
+
import warnings
|
| 10 |
+
from copy import copy, deepcopy
|
| 11 |
+
from functools import cached_property
|
| 12 |
+
from typing import (
|
| 13 |
+
TYPE_CHECKING,
|
| 14 |
+
Any,
|
| 15 |
+
Callable,
|
| 16 |
+
ClassVar,
|
| 17 |
+
Dict,
|
| 18 |
+
Generator,
|
| 19 |
+
Literal,
|
| 20 |
+
Mapping,
|
| 21 |
+
Set,
|
| 22 |
+
Tuple,
|
| 23 |
+
TypeVar,
|
| 24 |
+
Union,
|
| 25 |
+
cast,
|
| 26 |
+
overload,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
import pydantic_core
|
| 30 |
+
import typing_extensions
|
| 31 |
+
from pydantic_core import PydanticUndefined
|
| 32 |
+
from typing_extensions import Self, TypeAlias, Unpack
|
| 33 |
+
|
| 34 |
+
from ._internal import (
|
| 35 |
+
_config,
|
| 36 |
+
_decorators,
|
| 37 |
+
_fields,
|
| 38 |
+
_forward_ref,
|
| 39 |
+
_generics,
|
| 40 |
+
_import_utils,
|
| 41 |
+
_mock_val_ser,
|
| 42 |
+
_model_construction,
|
| 43 |
+
_namespace_utils,
|
| 44 |
+
_repr,
|
| 45 |
+
_typing_extra,
|
| 46 |
+
_utils,
|
| 47 |
+
)
|
| 48 |
+
from ._migration import getattr_migration
|
| 49 |
+
from .aliases import AliasChoices, AliasPath
|
| 50 |
+
from .annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler
|
| 51 |
+
from .config import ConfigDict
|
| 52 |
+
from .errors import PydanticUndefinedAnnotation, PydanticUserError
|
| 53 |
+
from .json_schema import DEFAULT_REF_TEMPLATE, GenerateJsonSchema, JsonSchemaMode, JsonSchemaValue, model_json_schema
|
| 54 |
+
from .plugin._schema_validator import PluggableSchemaValidator
|
| 55 |
+
from .warnings import PydanticDeprecatedSince20
|
| 56 |
+
|
| 57 |
+
if TYPE_CHECKING:
|
| 58 |
+
from inspect import Signature
|
| 59 |
+
from pathlib import Path
|
| 60 |
+
|
| 61 |
+
from pydantic_core import CoreSchema, SchemaSerializer, SchemaValidator
|
| 62 |
+
|
| 63 |
+
from ._internal._namespace_utils import MappingNamespace
|
| 64 |
+
from ._internal._utils import AbstractSetIntStr, MappingIntStrAny
|
| 65 |
+
from .deprecated.parse import Protocol as DeprecatedParseProtocol
|
| 66 |
+
from .fields import ComputedFieldInfo, FieldInfo, ModelPrivateAttr
|
| 67 |
+
else:
|
| 68 |
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
| 69 |
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
| 70 |
+
DeprecationWarning = PydanticDeprecatedSince20
|
| 71 |
+
|
| 72 |
+
__all__ = 'BaseModel', 'create_model'
|
| 73 |
+
|
| 74 |
+
# Keep these type aliases available at runtime:
|
| 75 |
+
TupleGenerator: TypeAlias = Generator[Tuple[str, Any], None, None]
|
| 76 |
+
# NOTE: In reality, `bool` should be replaced by `Literal[True]` but mypy fails to correctly apply bidirectional
|
| 77 |
+
# type inference (e.g. when using `{'a': {'b': True}}`):
|
| 78 |
+
# NOTE: Keep this type alias in sync with the stub definition in `pydantic-core`:
|
| 79 |
+
IncEx: TypeAlias = Union[Set[int], Set[str], Mapping[int, Union['IncEx', bool]], Mapping[str, Union['IncEx', bool]]]
|
| 80 |
+
|
| 81 |
+
_object_setattr = _model_construction.object_setattr
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class BaseModel(metaclass=_model_construction.ModelMetaclass):
|
| 85 |
+
"""Usage docs: https://docs.pydantic.dev/2.10/concepts/models/
|
| 86 |
+
|
| 87 |
+
A base class for creating Pydantic models.
|
| 88 |
+
|
| 89 |
+
Attributes:
|
| 90 |
+
__class_vars__: The names of the class variables defined on the model.
|
| 91 |
+
__private_attributes__: Metadata about the private attributes of the model.
|
| 92 |
+
__signature__: The synthesized `__init__` [`Signature`][inspect.Signature] of the model.
|
| 93 |
+
|
| 94 |
+
__pydantic_complete__: Whether model building is completed, or if there are still undefined fields.
|
| 95 |
+
__pydantic_core_schema__: The core schema of the model.
|
| 96 |
+
__pydantic_custom_init__: Whether the model has a custom `__init__` function.
|
| 97 |
+
__pydantic_decorators__: Metadata containing the decorators defined on the model.
|
| 98 |
+
This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1.
|
| 99 |
+
__pydantic_generic_metadata__: Metadata for generic models; contains data used for a similar purpose to
|
| 100 |
+
__args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these.
|
| 101 |
+
__pydantic_parent_namespace__: Parent namespace of the model, used for automatic rebuilding of models.
|
| 102 |
+
__pydantic_post_init__: The name of the post-init method for the model, if defined.
|
| 103 |
+
__pydantic_root_model__: Whether the model is a [`RootModel`][pydantic.root_model.RootModel].
|
| 104 |
+
__pydantic_serializer__: The `pydantic-core` `SchemaSerializer` used to dump instances of the model.
|
| 105 |
+
__pydantic_validator__: The `pydantic-core` `SchemaValidator` used to validate instances of the model.
|
| 106 |
+
|
| 107 |
+
__pydantic_fields__: A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects.
|
| 108 |
+
__pydantic_computed_fields__: A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects.
|
| 109 |
+
|
| 110 |
+
__pydantic_extra__: A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra]
|
| 111 |
+
is set to `'allow'`.
|
| 112 |
+
__pydantic_fields_set__: The names of fields explicitly set during instantiation.
|
| 113 |
+
__pydantic_private__: Values of private attributes set on the model instance.
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
# Note: Many of the below class vars are defined in the metaclass, but we define them here for type checking purposes.
|
| 117 |
+
|
| 118 |
+
model_config: ClassVar[ConfigDict] = ConfigDict()
|
| 119 |
+
"""
|
| 120 |
+
Configuration for the model, should be a dictionary conforming to [`ConfigDict`][pydantic.config.ConfigDict].
|
| 121 |
+
"""
|
| 122 |
+
|
| 123 |
+
# Because `dict` is in the local namespace of the `BaseModel` class, we use `Dict` for annotations.
|
| 124 |
+
# TODO v3 fallback to `dict` when the deprecated `dict` method gets removed.
|
| 125 |
+
__class_vars__: ClassVar[set[str]]
|
| 126 |
+
"""The names of the class variables defined on the model."""
|
| 127 |
+
|
| 128 |
+
__private_attributes__: ClassVar[Dict[str, ModelPrivateAttr]] # noqa: UP006
|
| 129 |
+
"""Metadata about the private attributes of the model."""
|
| 130 |
+
|
| 131 |
+
__signature__: ClassVar[Signature]
|
| 132 |
+
"""The synthesized `__init__` [`Signature`][inspect.Signature] of the model."""
|
| 133 |
+
|
| 134 |
+
__pydantic_complete__: ClassVar[bool] = False
|
| 135 |
+
"""Whether model building is completed, or if there are still undefined fields."""
|
| 136 |
+
|
| 137 |
+
__pydantic_core_schema__: ClassVar[CoreSchema]
|
| 138 |
+
"""The core schema of the model."""
|
| 139 |
+
|
| 140 |
+
__pydantic_custom_init__: ClassVar[bool]
|
| 141 |
+
"""Whether the model has a custom `__init__` method."""
|
| 142 |
+
|
| 143 |
+
# Must be set for `GenerateSchema.model_schema` to work for a plain `BaseModel` annotation.
|
| 144 |
+
__pydantic_decorators__: ClassVar[_decorators.DecoratorInfos] = _decorators.DecoratorInfos()
|
| 145 |
+
"""Metadata containing the decorators defined on the model.
|
| 146 |
+
This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1."""
|
| 147 |
+
|
| 148 |
+
__pydantic_generic_metadata__: ClassVar[_generics.PydanticGenericMetadata]
|
| 149 |
+
"""Metadata for generic models; contains data used for a similar purpose to
|
| 150 |
+
__args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these."""
|
| 151 |
+
|
| 152 |
+
__pydantic_parent_namespace__: ClassVar[Dict[str, Any] | None] = None # noqa: UP006
|
| 153 |
+
"""Parent namespace of the model, used for automatic rebuilding of models."""
|
| 154 |
+
|
| 155 |
+
__pydantic_post_init__: ClassVar[None | Literal['model_post_init']]
|
| 156 |
+
"""The name of the post-init method for the model, if defined."""
|
| 157 |
+
|
| 158 |
+
__pydantic_root_model__: ClassVar[bool] = False
|
| 159 |
+
"""Whether the model is a [`RootModel`][pydantic.root_model.RootModel]."""
|
| 160 |
+
|
| 161 |
+
__pydantic_serializer__: ClassVar[SchemaSerializer]
|
| 162 |
+
"""The `pydantic-core` `SchemaSerializer` used to dump instances of the model."""
|
| 163 |
+
|
| 164 |
+
__pydantic_validator__: ClassVar[SchemaValidator | PluggableSchemaValidator]
|
| 165 |
+
"""The `pydantic-core` `SchemaValidator` used to validate instances of the model."""
|
| 166 |
+
|
| 167 |
+
__pydantic_fields__: ClassVar[Dict[str, FieldInfo]] # noqa: UP006
|
| 168 |
+
"""A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects.
|
| 169 |
+
This replaces `Model.__fields__` from Pydantic V1.
|
| 170 |
+
"""
|
| 171 |
+
|
| 172 |
+
__pydantic_computed_fields__: ClassVar[Dict[str, ComputedFieldInfo]] # noqa: UP006
|
| 173 |
+
"""A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects."""
|
| 174 |
+
|
| 175 |
+
__pydantic_extra__: dict[str, Any] | None = _model_construction.NoInitField(init=False)
|
| 176 |
+
"""A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra] is set to `'allow'`."""
|
| 177 |
+
|
| 178 |
+
__pydantic_fields_set__: set[str] = _model_construction.NoInitField(init=False)
|
| 179 |
+
"""The names of fields explicitly set during instantiation."""
|
| 180 |
+
|
| 181 |
+
__pydantic_private__: dict[str, Any] | None = _model_construction.NoInitField(init=False)
|
| 182 |
+
"""Values of private attributes set on the model instance."""
|
| 183 |
+
|
| 184 |
+
if not TYPE_CHECKING:
|
| 185 |
+
# Prevent `BaseModel` from being instantiated directly
|
| 186 |
+
# (defined in an `if not TYPE_CHECKING` block for clarity and to avoid type checking errors):
|
| 187 |
+
__pydantic_core_schema__ = _mock_val_ser.MockCoreSchema(
|
| 188 |
+
'Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly',
|
| 189 |
+
code='base-model-instantiated',
|
| 190 |
+
)
|
| 191 |
+
__pydantic_validator__ = _mock_val_ser.MockValSer(
|
| 192 |
+
'Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly',
|
| 193 |
+
val_or_ser='validator',
|
| 194 |
+
code='base-model-instantiated',
|
| 195 |
+
)
|
| 196 |
+
__pydantic_serializer__ = _mock_val_ser.MockValSer(
|
| 197 |
+
'Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly',
|
| 198 |
+
val_or_ser='serializer',
|
| 199 |
+
code='base-model-instantiated',
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
__slots__ = '__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__'
|
| 203 |
+
|
| 204 |
+
def __init__(self, /, **data: Any) -> None:
|
| 205 |
+
"""Create a new model by parsing and validating input data from keyword arguments.
|
| 206 |
+
|
| 207 |
+
Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
|
| 208 |
+
validated to form a valid model.
|
| 209 |
+
|
| 210 |
+
`self` is explicitly positional-only to allow `self` as a field name.
|
| 211 |
+
"""
|
| 212 |
+
# `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
|
| 213 |
+
__tracebackhide__ = True
|
| 214 |
+
validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
|
| 215 |
+
if self is not validated_self:
|
| 216 |
+
warnings.warn(
|
| 217 |
+
'A custom validator is returning a value other than `self`.\n'
|
| 218 |
+
"Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
|
| 219 |
+
'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
|
| 220 |
+
stacklevel=2,
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
# The following line sets a flag that we use to determine when `__init__` gets overridden by the user
|
| 224 |
+
__init__.__pydantic_base_init__ = True # pyright: ignore[reportFunctionMemberAccess]
|
| 225 |
+
|
| 226 |
+
if TYPE_CHECKING:
|
| 227 |
+
model_fields: ClassVar[dict[str, FieldInfo]]
|
| 228 |
+
model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]]
|
| 229 |
+
else:
|
| 230 |
+
# TODO: V3 - remove `model_fields` and `model_computed_fields` properties from the `BaseModel` class - they should only
|
| 231 |
+
# be accessible on the model class, not on instances. We have these purely for backwards compatibility with Pydantic <v2.10.
|
| 232 |
+
# This is similar to the fact that we have __fields__ defined here (on `BaseModel`) and on `ModelMetaClass`.
|
| 233 |
+
# Another problem here is that there's no great way to have class properties :(
|
| 234 |
+
@property
|
| 235 |
+
def model_fields(self) -> dict[str, FieldInfo]:
|
| 236 |
+
"""Get metadata about the fields defined on the model.
|
| 237 |
+
|
| 238 |
+
Deprecation warning: you should be getting this information from the model class, not from an instance.
|
| 239 |
+
In V3, this property will be removed from the `BaseModel` class.
|
| 240 |
+
|
| 241 |
+
Returns:
|
| 242 |
+
A mapping of field names to [`FieldInfo`][pydantic.fields.FieldInfo] objects.
|
| 243 |
+
"""
|
| 244 |
+
# Must be set for `GenerateSchema.model_schema` to work for a plain `BaseModel` annotation, hence the default here.
|
| 245 |
+
return getattr(self, '__pydantic_fields__', {})
|
| 246 |
+
|
| 247 |
+
@property
|
| 248 |
+
def model_computed_fields(self) -> dict[str, ComputedFieldInfo]:
|
| 249 |
+
"""Get metadata about the computed fields defined on the model.
|
| 250 |
+
|
| 251 |
+
Deprecation warning: you should be getting this information from the model class, not from an instance.
|
| 252 |
+
In V3, this property will be removed from the `BaseModel` class.
|
| 253 |
+
|
| 254 |
+
Returns:
|
| 255 |
+
A mapping of computed field names to [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects.
|
| 256 |
+
"""
|
| 257 |
+
# Must be set for `GenerateSchema.model_schema` to work for a plain `BaseModel` annotation, hence the default here.
|
| 258 |
+
return getattr(self, '__pydantic_computed_fields__', {})
|
| 259 |
+
|
| 260 |
+
@property
|
| 261 |
+
def model_extra(self) -> dict[str, Any] | None:
|
| 262 |
+
"""Get extra fields set during validation.
|
| 263 |
+
|
| 264 |
+
Returns:
|
| 265 |
+
A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| 266 |
+
"""
|
| 267 |
+
return self.__pydantic_extra__
|
| 268 |
+
|
| 269 |
+
@property
|
| 270 |
+
def model_fields_set(self) -> set[str]:
|
| 271 |
+
"""Returns the set of fields that have been explicitly set on this model instance.
|
| 272 |
+
|
| 273 |
+
Returns:
|
| 274 |
+
A set of strings representing the fields that have been set,
|
| 275 |
+
i.e. that were not filled from defaults.
|
| 276 |
+
"""
|
| 277 |
+
return self.__pydantic_fields_set__
|
| 278 |
+
|
| 279 |
+
@classmethod
|
| 280 |
+
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self: # noqa: C901
|
| 281 |
+
"""Creates a new instance of the `Model` class with validated data.
|
| 282 |
+
|
| 283 |
+
Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
|
| 284 |
+
Default values are respected, but no other validation is performed.
|
| 285 |
+
|
| 286 |
+
!!! note
|
| 287 |
+
`model_construct()` generally respects the `model_config.extra` setting on the provided model.
|
| 288 |
+
That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
|
| 289 |
+
and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
|
| 290 |
+
Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
|
| 291 |
+
an error if extra values are passed, but they will be ignored.
|
| 292 |
+
|
| 293 |
+
Args:
|
| 294 |
+
_fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
|
| 295 |
+
this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
|
| 296 |
+
Otherwise, the field names from the `values` argument will be used.
|
| 297 |
+
values: Trusted or pre-validated data dictionary.
|
| 298 |
+
|
| 299 |
+
Returns:
|
| 300 |
+
A new instance of the `Model` class with validated data.
|
| 301 |
+
"""
|
| 302 |
+
m = cls.__new__(cls)
|
| 303 |
+
fields_values: dict[str, Any] = {}
|
| 304 |
+
fields_set = set()
|
| 305 |
+
|
| 306 |
+
for name, field in cls.__pydantic_fields__.items():
|
| 307 |
+
if field.alias is not None and field.alias in values:
|
| 308 |
+
fields_values[name] = values.pop(field.alias)
|
| 309 |
+
fields_set.add(name)
|
| 310 |
+
|
| 311 |
+
if (name not in fields_set) and (field.validation_alias is not None):
|
| 312 |
+
validation_aliases: list[str | AliasPath] = (
|
| 313 |
+
field.validation_alias.choices
|
| 314 |
+
if isinstance(field.validation_alias, AliasChoices)
|
| 315 |
+
else [field.validation_alias]
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
for alias in validation_aliases:
|
| 319 |
+
if isinstance(alias, str) and alias in values:
|
| 320 |
+
fields_values[name] = values.pop(alias)
|
| 321 |
+
fields_set.add(name)
|
| 322 |
+
break
|
| 323 |
+
elif isinstance(alias, AliasPath):
|
| 324 |
+
value = alias.search_dict_for_path(values)
|
| 325 |
+
if value is not PydanticUndefined:
|
| 326 |
+
fields_values[name] = value
|
| 327 |
+
fields_set.add(name)
|
| 328 |
+
break
|
| 329 |
+
|
| 330 |
+
if name not in fields_set:
|
| 331 |
+
if name in values:
|
| 332 |
+
fields_values[name] = values.pop(name)
|
| 333 |
+
fields_set.add(name)
|
| 334 |
+
elif not field.is_required():
|
| 335 |
+
fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
|
| 336 |
+
if _fields_set is None:
|
| 337 |
+
_fields_set = fields_set
|
| 338 |
+
|
| 339 |
+
_extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
|
| 340 |
+
_object_setattr(m, '__dict__', fields_values)
|
| 341 |
+
_object_setattr(m, '__pydantic_fields_set__', _fields_set)
|
| 342 |
+
if not cls.__pydantic_root_model__:
|
| 343 |
+
_object_setattr(m, '__pydantic_extra__', _extra)
|
| 344 |
+
|
| 345 |
+
if cls.__pydantic_post_init__:
|
| 346 |
+
m.model_post_init(None)
|
| 347 |
+
# update private attributes with values set
|
| 348 |
+
if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
|
| 349 |
+
for k, v in values.items():
|
| 350 |
+
if k in m.__private_attributes__:
|
| 351 |
+
m.__pydantic_private__[k] = v
|
| 352 |
+
|
| 353 |
+
elif not cls.__pydantic_root_model__:
|
| 354 |
+
# Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
|
| 355 |
+
# Since it doesn't, that means that `__pydantic_private__` should be set to None
|
| 356 |
+
_object_setattr(m, '__pydantic_private__', None)
|
| 357 |
+
|
| 358 |
+
return m
|
| 359 |
+
|
| 360 |
+
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
|
| 361 |
+
"""Usage docs: https://docs.pydantic.dev/2.10/concepts/serialization/#model_copy
|
| 362 |
+
|
| 363 |
+
Returns a copy of the model.
|
| 364 |
+
|
| 365 |
+
Args:
|
| 366 |
+
update: Values to change/add in the new model. Note: the data is not validated
|
| 367 |
+
before creating the new model. You should trust this data.
|
| 368 |
+
deep: Set to `True` to make a deep copy of the model.
|
| 369 |
+
|
| 370 |
+
Returns:
|
| 371 |
+
New model instance.
|
| 372 |
+
"""
|
| 373 |
+
copied = self.__deepcopy__() if deep else self.__copy__()
|
| 374 |
+
if update:
|
| 375 |
+
if self.model_config.get('extra') == 'allow':
|
| 376 |
+
for k, v in update.items():
|
| 377 |
+
if k in self.__pydantic_fields__:
|
| 378 |
+
copied.__dict__[k] = v
|
| 379 |
+
else:
|
| 380 |
+
if copied.__pydantic_extra__ is None:
|
| 381 |
+
copied.__pydantic_extra__ = {}
|
| 382 |
+
copied.__pydantic_extra__[k] = v
|
| 383 |
+
else:
|
| 384 |
+
copied.__dict__.update(update)
|
| 385 |
+
copied.__pydantic_fields_set__.update(update.keys())
|
| 386 |
+
return copied
|
| 387 |
+
|
| 388 |
+
def model_dump(
|
| 389 |
+
self,
|
| 390 |
+
*,
|
| 391 |
+
mode: Literal['json', 'python'] | str = 'python',
|
| 392 |
+
include: IncEx | None = None,
|
| 393 |
+
exclude: IncEx | None = None,
|
| 394 |
+
context: Any | None = None,
|
| 395 |
+
by_alias: bool = False,
|
| 396 |
+
exclude_unset: bool = False,
|
| 397 |
+
exclude_defaults: bool = False,
|
| 398 |
+
exclude_none: bool = False,
|
| 399 |
+
round_trip: bool = False,
|
| 400 |
+
warnings: bool | Literal['none', 'warn', 'error'] = True,
|
| 401 |
+
serialize_as_any: bool = False,
|
| 402 |
+
) -> dict[str, Any]:
|
| 403 |
+
"""Usage docs: https://docs.pydantic.dev/2.10/concepts/serialization/#modelmodel_dump
|
| 404 |
+
|
| 405 |
+
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| 406 |
+
|
| 407 |
+
Args:
|
| 408 |
+
mode: The mode in which `to_python` should run.
|
| 409 |
+
If mode is 'json', the output will only contain JSON serializable types.
|
| 410 |
+
If mode is 'python', the output may contain non-JSON-serializable Python objects.
|
| 411 |
+
include: A set of fields to include in the output.
|
| 412 |
+
exclude: A set of fields to exclude from the output.
|
| 413 |
+
context: Additional context to pass to the serializer.
|
| 414 |
+
by_alias: Whether to use the field's alias in the dictionary key if defined.
|
| 415 |
+
exclude_unset: Whether to exclude fields that have not been explicitly set.
|
| 416 |
+
exclude_defaults: Whether to exclude fields that are set to their default value.
|
| 417 |
+
exclude_none: Whether to exclude fields that have a value of `None`.
|
| 418 |
+
round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
|
| 419 |
+
warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
|
| 420 |
+
"error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
|
| 421 |
+
serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
|
| 422 |
+
|
| 423 |
+
Returns:
|
| 424 |
+
A dictionary representation of the model.
|
| 425 |
+
"""
|
| 426 |
+
return self.__pydantic_serializer__.to_python(
|
| 427 |
+
self,
|
| 428 |
+
mode=mode,
|
| 429 |
+
by_alias=by_alias,
|
| 430 |
+
include=include,
|
| 431 |
+
exclude=exclude,
|
| 432 |
+
context=context,
|
| 433 |
+
exclude_unset=exclude_unset,
|
| 434 |
+
exclude_defaults=exclude_defaults,
|
| 435 |
+
exclude_none=exclude_none,
|
| 436 |
+
round_trip=round_trip,
|
| 437 |
+
warnings=warnings,
|
| 438 |
+
serialize_as_any=serialize_as_any,
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
def model_dump_json(
|
| 442 |
+
self,
|
| 443 |
+
*,
|
| 444 |
+
indent: int | None = None,
|
| 445 |
+
include: IncEx | None = None,
|
| 446 |
+
exclude: IncEx | None = None,
|
| 447 |
+
context: Any | None = None,
|
| 448 |
+
by_alias: bool = False,
|
| 449 |
+
exclude_unset: bool = False,
|
| 450 |
+
exclude_defaults: bool = False,
|
| 451 |
+
exclude_none: bool = False,
|
| 452 |
+
round_trip: bool = False,
|
| 453 |
+
warnings: bool | Literal['none', 'warn', 'error'] = True,
|
| 454 |
+
serialize_as_any: bool = False,
|
| 455 |
+
) -> str:
|
| 456 |
+
"""Usage docs: https://docs.pydantic.dev/2.10/concepts/serialization/#modelmodel_dump_json
|
| 457 |
+
|
| 458 |
+
Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| 459 |
+
|
| 460 |
+
Args:
|
| 461 |
+
indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
|
| 462 |
+
include: Field(s) to include in the JSON output.
|
| 463 |
+
exclude: Field(s) to exclude from the JSON output.
|
| 464 |
+
context: Additional context to pass to the serializer.
|
| 465 |
+
by_alias: Whether to serialize using field aliases.
|
| 466 |
+
exclude_unset: Whether to exclude fields that have not been explicitly set.
|
| 467 |
+
exclude_defaults: Whether to exclude fields that are set to their default value.
|
| 468 |
+
exclude_none: Whether to exclude fields that have a value of `None`.
|
| 469 |
+
round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
|
| 470 |
+
warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
|
| 471 |
+
"error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
|
| 472 |
+
serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
|
| 473 |
+
|
| 474 |
+
Returns:
|
| 475 |
+
A JSON string representation of the model.
|
| 476 |
+
"""
|
| 477 |
+
return self.__pydantic_serializer__.to_json(
|
| 478 |
+
self,
|
| 479 |
+
indent=indent,
|
| 480 |
+
include=include,
|
| 481 |
+
exclude=exclude,
|
| 482 |
+
context=context,
|
| 483 |
+
by_alias=by_alias,
|
| 484 |
+
exclude_unset=exclude_unset,
|
| 485 |
+
exclude_defaults=exclude_defaults,
|
| 486 |
+
exclude_none=exclude_none,
|
| 487 |
+
round_trip=round_trip,
|
| 488 |
+
warnings=warnings,
|
| 489 |
+
serialize_as_any=serialize_as_any,
|
| 490 |
+
).decode()
|
| 491 |
+
|
| 492 |
+
@classmethod
|
| 493 |
+
def model_json_schema(
|
| 494 |
+
cls,
|
| 495 |
+
by_alias: bool = True,
|
| 496 |
+
ref_template: str = DEFAULT_REF_TEMPLATE,
|
| 497 |
+
schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
|
| 498 |
+
mode: JsonSchemaMode = 'validation',
|
| 499 |
+
) -> dict[str, Any]:
|
| 500 |
+
"""Generates a JSON schema for a model class.
|
| 501 |
+
|
| 502 |
+
Args:
|
| 503 |
+
by_alias: Whether to use attribute aliases or not.
|
| 504 |
+
ref_template: The reference template.
|
| 505 |
+
schema_generator: To override the logic used to generate the JSON schema, as a subclass of
|
| 506 |
+
`GenerateJsonSchema` with your desired modifications
|
| 507 |
+
mode: The mode in which to generate the schema.
|
| 508 |
+
|
| 509 |
+
Returns:
|
| 510 |
+
The JSON schema for the given model class.
|
| 511 |
+
"""
|
| 512 |
+
return model_json_schema(
|
| 513 |
+
cls, by_alias=by_alias, ref_template=ref_template, schema_generator=schema_generator, mode=mode
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
@classmethod
|
| 517 |
+
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
|
| 518 |
+
"""Compute the class name for parametrizations of generic classes.
|
| 519 |
+
|
| 520 |
+
This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| 521 |
+
|
| 522 |
+
Args:
|
| 523 |
+
params: Tuple of types of the class. Given a generic class
|
| 524 |
+
`Model` with 2 type variables and a concrete model `Model[str, int]`,
|
| 525 |
+
the value `(str, int)` would be passed to `params`.
|
| 526 |
+
|
| 527 |
+
Returns:
|
| 528 |
+
String representing the new class where `params` are passed to `cls` as type variables.
|
| 529 |
+
|
| 530 |
+
Raises:
|
| 531 |
+
TypeError: Raised when trying to generate concrete names for non-generic models.
|
| 532 |
+
"""
|
| 533 |
+
if not issubclass(cls, typing.Generic):
|
| 534 |
+
raise TypeError('Concrete names should only be generated for generic models.')
|
| 535 |
+
|
| 536 |
+
# Any strings received should represent forward references, so we handle them specially below.
|
| 537 |
+
# If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
|
| 538 |
+
# we may be able to remove this special case.
|
| 539 |
+
param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
|
| 540 |
+
params_component = ', '.join(param_names)
|
| 541 |
+
return f'{cls.__name__}[{params_component}]'
|
| 542 |
+
|
| 543 |
+
def model_post_init(self, __context: Any) -> None:
|
| 544 |
+
"""Override this method to perform additional initialization after `__init__` and `model_construct`.
|
| 545 |
+
This is useful if you want to do some validation that requires the entire model to be initialized.
|
| 546 |
+
"""
|
| 547 |
+
pass
|
| 548 |
+
|
| 549 |
+
@classmethod
|
| 550 |
+
def model_rebuild(
|
| 551 |
+
cls,
|
| 552 |
+
*,
|
| 553 |
+
force: bool = False,
|
| 554 |
+
raise_errors: bool = True,
|
| 555 |
+
_parent_namespace_depth: int = 2,
|
| 556 |
+
_types_namespace: MappingNamespace | None = None,
|
| 557 |
+
) -> bool | None:
|
| 558 |
+
"""Try to rebuild the pydantic-core schema for the model.
|
| 559 |
+
|
| 560 |
+
This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
|
| 561 |
+
the initial attempt to build the schema, and automatic rebuilding fails.
|
| 562 |
+
|
| 563 |
+
Args:
|
| 564 |
+
force: Whether to force the rebuilding of the model schema, defaults to `False`.
|
| 565 |
+
raise_errors: Whether to raise errors, defaults to `True`.
|
| 566 |
+
_parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
|
| 567 |
+
_types_namespace: The types namespace, defaults to `None`.
|
| 568 |
+
|
| 569 |
+
Returns:
|
| 570 |
+
Returns `None` if the schema is already "complete" and rebuilding was not required.
|
| 571 |
+
If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| 572 |
+
"""
|
| 573 |
+
if not force and cls.__pydantic_complete__:
|
| 574 |
+
return None
|
| 575 |
+
|
| 576 |
+
if '__pydantic_core_schema__' in cls.__dict__:
|
| 577 |
+
delattr(cls, '__pydantic_core_schema__') # delete cached value to ensure full rebuild happens
|
| 578 |
+
|
| 579 |
+
if _types_namespace is not None:
|
| 580 |
+
rebuild_ns = _types_namespace
|
| 581 |
+
elif _parent_namespace_depth > 0:
|
| 582 |
+
rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
|
| 583 |
+
else:
|
| 584 |
+
rebuild_ns = {}
|
| 585 |
+
|
| 586 |
+
parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}
|
| 587 |
+
|
| 588 |
+
ns_resolver = _namespace_utils.NsResolver(
|
| 589 |
+
parent_namespace={**rebuild_ns, **parent_ns},
|
| 590 |
+
)
|
| 591 |
+
|
| 592 |
+
# manually override defer_build so complete_model_class doesn't skip building the model again
|
| 593 |
+
config = {**cls.model_config, 'defer_build': False}
|
| 594 |
+
return _model_construction.complete_model_class(
|
| 595 |
+
cls,
|
| 596 |
+
cls.__name__,
|
| 597 |
+
_config.ConfigWrapper(config, check=False),
|
| 598 |
+
raise_errors=raise_errors,
|
| 599 |
+
ns_resolver=ns_resolver,
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
@classmethod
|
| 603 |
+
def model_validate(
|
| 604 |
+
cls,
|
| 605 |
+
obj: Any,
|
| 606 |
+
*,
|
| 607 |
+
strict: bool | None = None,
|
| 608 |
+
from_attributes: bool | None = None,
|
| 609 |
+
context: Any | None = None,
|
| 610 |
+
) -> Self:
|
| 611 |
+
"""Validate a pydantic model instance.
|
| 612 |
+
|
| 613 |
+
Args:
|
| 614 |
+
obj: The object to validate.
|
| 615 |
+
strict: Whether to enforce types strictly.
|
| 616 |
+
from_attributes: Whether to extract data from object attributes.
|
| 617 |
+
context: Additional context to pass to the validator.
|
| 618 |
+
|
| 619 |
+
Raises:
|
| 620 |
+
ValidationError: If the object could not be validated.
|
| 621 |
+
|
| 622 |
+
Returns:
|
| 623 |
+
The validated model instance.
|
| 624 |
+
"""
|
| 625 |
+
# `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
|
| 626 |
+
__tracebackhide__ = True
|
| 627 |
+
return cls.__pydantic_validator__.validate_python(
|
| 628 |
+
obj, strict=strict, from_attributes=from_attributes, context=context
|
| 629 |
+
)
|
| 630 |
+
|
| 631 |
+
@classmethod
|
| 632 |
+
def model_validate_json(
|
| 633 |
+
cls,
|
| 634 |
+
json_data: str | bytes | bytearray,
|
| 635 |
+
*,
|
| 636 |
+
strict: bool | None = None,
|
| 637 |
+
context: Any | None = None,
|
| 638 |
+
) -> Self:
|
| 639 |
+
"""Usage docs: https://docs.pydantic.dev/2.10/concepts/json/#json-parsing
|
| 640 |
+
|
| 641 |
+
Validate the given JSON data against the Pydantic model.
|
| 642 |
+
|
| 643 |
+
Args:
|
| 644 |
+
json_data: The JSON data to validate.
|
| 645 |
+
strict: Whether to enforce types strictly.
|
| 646 |
+
context: Extra variables to pass to the validator.
|
| 647 |
+
|
| 648 |
+
Returns:
|
| 649 |
+
The validated Pydantic model.
|
| 650 |
+
|
| 651 |
+
Raises:
|
| 652 |
+
ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| 653 |
+
"""
|
| 654 |
+
# `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
|
| 655 |
+
__tracebackhide__ = True
|
| 656 |
+
return cls.__pydantic_validator__.validate_json(json_data, strict=strict, context=context)
|
| 657 |
+
|
| 658 |
+
@classmethod
|
| 659 |
+
def model_validate_strings(
|
| 660 |
+
cls,
|
| 661 |
+
obj: Any,
|
| 662 |
+
*,
|
| 663 |
+
strict: bool | None = None,
|
| 664 |
+
context: Any | None = None,
|
| 665 |
+
) -> Self:
|
| 666 |
+
"""Validate the given object with string data against the Pydantic model.
|
| 667 |
+
|
| 668 |
+
Args:
|
| 669 |
+
obj: The object containing string data to validate.
|
| 670 |
+
strict: Whether to enforce types strictly.
|
| 671 |
+
context: Extra variables to pass to the validator.
|
| 672 |
+
|
| 673 |
+
Returns:
|
| 674 |
+
The validated Pydantic model.
|
| 675 |
+
"""
|
| 676 |
+
# `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
|
| 677 |
+
__tracebackhide__ = True
|
| 678 |
+
return cls.__pydantic_validator__.validate_strings(obj, strict=strict, context=context)
|
| 679 |
+
|
| 680 |
+
@classmethod
|
| 681 |
+
def __get_pydantic_core_schema__(cls, source: type[BaseModel], handler: GetCoreSchemaHandler, /) -> CoreSchema:
|
| 682 |
+
"""Hook into generating the model's CoreSchema.
|
| 683 |
+
|
| 684 |
+
Args:
|
| 685 |
+
source: The class we are generating a schema for.
|
| 686 |
+
This will generally be the same as the `cls` argument if this is a classmethod.
|
| 687 |
+
handler: A callable that calls into Pydantic's internal CoreSchema generation logic.
|
| 688 |
+
|
| 689 |
+
Returns:
|
| 690 |
+
A `pydantic-core` `CoreSchema`.
|
| 691 |
+
"""
|
| 692 |
+
# Only use the cached value from this _exact_ class; we don't want one from a parent class
|
| 693 |
+
# This is why we check `cls.__dict__` and don't use `cls.__pydantic_core_schema__` or similar.
|
| 694 |
+
schema = cls.__dict__.get('__pydantic_core_schema__')
|
| 695 |
+
if schema is not None and not isinstance(schema, _mock_val_ser.MockCoreSchema):
|
| 696 |
+
# Due to the way generic classes are built, it's possible that an invalid schema may be temporarily
|
| 697 |
+
# set on generic classes. I think we could resolve this to ensure that we get proper schema caching
|
| 698 |
+
# for generics, but for simplicity for now, we just always rebuild if the class has a generic origin.
|
| 699 |
+
if not cls.__pydantic_generic_metadata__['origin']:
|
| 700 |
+
return cls.__pydantic_core_schema__
|
| 701 |
+
|
| 702 |
+
return handler(source)
|
| 703 |
+
|
| 704 |
+
@classmethod
|
| 705 |
+
def __get_pydantic_json_schema__(
|
| 706 |
+
cls,
|
| 707 |
+
core_schema: CoreSchema,
|
| 708 |
+
handler: GetJsonSchemaHandler,
|
| 709 |
+
/,
|
| 710 |
+
) -> JsonSchemaValue:
|
| 711 |
+
"""Hook into generating the model's JSON schema.
|
| 712 |
+
|
| 713 |
+
Args:
|
| 714 |
+
core_schema: A `pydantic-core` CoreSchema.
|
| 715 |
+
You can ignore this argument and call the handler with a new CoreSchema,
|
| 716 |
+
wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
|
| 717 |
+
or just call the handler with the original schema.
|
| 718 |
+
handler: Call into Pydantic's internal JSON schema generation.
|
| 719 |
+
This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
|
| 720 |
+
generation fails.
|
| 721 |
+
Since this gets called by `BaseModel.model_json_schema` you can override the
|
| 722 |
+
`schema_generator` argument to that function to change JSON schema generation globally
|
| 723 |
+
for a type.
|
| 724 |
+
|
| 725 |
+
Returns:
|
| 726 |
+
A JSON schema, as a Python object.
|
| 727 |
+
"""
|
| 728 |
+
return handler(core_schema)
|
| 729 |
+
|
| 730 |
+
@classmethod
|
| 731 |
+
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
|
| 732 |
+
"""This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
|
| 733 |
+
only after the class is actually fully initialized. In particular, attributes like `model_fields` will
|
| 734 |
+
be present when this is called.
|
| 735 |
+
|
| 736 |
+
This is necessary because `__init_subclass__` will always be called by `type.__new__`,
|
| 737 |
+
and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
|
| 738 |
+
`type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| 739 |
+
|
| 740 |
+
This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
|
| 741 |
+
any kwargs passed to the class definition that aren't used internally by pydantic.
|
| 742 |
+
|
| 743 |
+
Args:
|
| 744 |
+
**kwargs: Any keyword arguments passed to the class definition that aren't used internally
|
| 745 |
+
by pydantic.
|
| 746 |
+
"""
|
| 747 |
+
pass
|
| 748 |
+
|
| 749 |
+
def __class_getitem__(
|
| 750 |
+
cls, typevar_values: type[Any] | tuple[type[Any], ...]
|
| 751 |
+
) -> type[BaseModel] | _forward_ref.PydanticRecursiveRef:
|
| 752 |
+
cached = _generics.get_cached_generic_type_early(cls, typevar_values)
|
| 753 |
+
if cached is not None:
|
| 754 |
+
return cached
|
| 755 |
+
|
| 756 |
+
if cls is BaseModel:
|
| 757 |
+
raise TypeError('Type parameters should be placed on typing.Generic, not BaseModel')
|
| 758 |
+
if not hasattr(cls, '__parameters__'):
|
| 759 |
+
raise TypeError(f'{cls} cannot be parametrized because it does not inherit from typing.Generic')
|
| 760 |
+
if not cls.__pydantic_generic_metadata__['parameters'] and typing.Generic not in cls.__bases__:
|
| 761 |
+
raise TypeError(f'{cls} is not a generic class')
|
| 762 |
+
|
| 763 |
+
if not isinstance(typevar_values, tuple):
|
| 764 |
+
typevar_values = (typevar_values,)
|
| 765 |
+
_generics.check_parameters_count(cls, typevar_values)
|
| 766 |
+
|
| 767 |
+
# Build map from generic typevars to passed params
|
| 768 |
+
typevars_map: dict[TypeVar, type[Any]] = dict(
|
| 769 |
+
zip(cls.__pydantic_generic_metadata__['parameters'], typevar_values)
|
| 770 |
+
)
|
| 771 |
+
|
| 772 |
+
if _utils.all_identical(typevars_map.keys(), typevars_map.values()) and typevars_map:
|
| 773 |
+
submodel = cls # if arguments are equal to parameters it's the same object
|
| 774 |
+
_generics.set_cached_generic_type(cls, typevar_values, submodel)
|
| 775 |
+
else:
|
| 776 |
+
parent_args = cls.__pydantic_generic_metadata__['args']
|
| 777 |
+
if not parent_args:
|
| 778 |
+
args = typevar_values
|
| 779 |
+
else:
|
| 780 |
+
args = tuple(_generics.replace_types(arg, typevars_map) for arg in parent_args)
|
| 781 |
+
|
| 782 |
+
origin = cls.__pydantic_generic_metadata__['origin'] or cls
|
| 783 |
+
model_name = origin.model_parametrized_name(args)
|
| 784 |
+
params = tuple(
|
| 785 |
+
{param: None for param in _generics.iter_contained_typevars(typevars_map.values())}
|
| 786 |
+
) # use dict as ordered set
|
| 787 |
+
|
| 788 |
+
with _generics.generic_recursion_self_type(origin, args) as maybe_self_type:
|
| 789 |
+
# Check cached first otherwise `mro` may return `PydanticRecursiveRef`
|
| 790 |
+
cached = _generics.get_cached_generic_type_late(cls, typevar_values, origin, args)
|
| 791 |
+
if cached is not None:
|
| 792 |
+
return cached
|
| 793 |
+
|
| 794 |
+
if maybe_self_type is not None:
|
| 795 |
+
return maybe_self_type
|
| 796 |
+
|
| 797 |
+
# Attempt to rebuild the origin in case new types have been defined
|
| 798 |
+
try:
|
| 799 |
+
# depth 2 gets you above this __class_getitem__ call.
|
| 800 |
+
# Note that we explicitly provide the parent ns, otherwise
|
| 801 |
+
# `model_rebuild` will use the parent ns no matter if it is the ns of a module.
|
| 802 |
+
# We don't want this here, as this has unexpected effects when a model
|
| 803 |
+
# is being parametrized during a forward annotation evaluation.
|
| 804 |
+
parent_ns = _typing_extra.parent_frame_namespace(parent_depth=2) or {}
|
| 805 |
+
origin.model_rebuild(_types_namespace=parent_ns)
|
| 806 |
+
except PydanticUndefinedAnnotation:
|
| 807 |
+
# It's okay if it fails, it just means there are still undefined types
|
| 808 |
+
# that could be evaluated later.
|
| 809 |
+
pass
|
| 810 |
+
|
| 811 |
+
submodel = _generics.create_generic_submodel(model_name, origin, args, params)
|
| 812 |
+
|
| 813 |
+
# Update cache
|
| 814 |
+
_generics.set_cached_generic_type(cls, typevar_values, submodel, origin, args)
|
| 815 |
+
|
| 816 |
+
return submodel
|
| 817 |
+
|
| 818 |
+
def __copy__(self) -> Self:
|
| 819 |
+
"""Returns a shallow copy of the model."""
|
| 820 |
+
cls = type(self)
|
| 821 |
+
m = cls.__new__(cls)
|
| 822 |
+
_object_setattr(m, '__dict__', copy(self.__dict__))
|
| 823 |
+
_object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
|
| 824 |
+
_object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))
|
| 825 |
+
|
| 826 |
+
if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
|
| 827 |
+
_object_setattr(m, '__pydantic_private__', None)
|
| 828 |
+
else:
|
| 829 |
+
_object_setattr(
|
| 830 |
+
m,
|
| 831 |
+
'__pydantic_private__',
|
| 832 |
+
{k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
|
| 833 |
+
)
|
| 834 |
+
|
| 835 |
+
return m
|
| 836 |
+
|
| 837 |
+
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
|
| 838 |
+
"""Returns a deep copy of the model."""
|
| 839 |
+
cls = type(self)
|
| 840 |
+
m = cls.__new__(cls)
|
| 841 |
+
_object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
|
| 842 |
+
_object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
|
| 843 |
+
# This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
|
| 844 |
+
# and attempting a deepcopy would be marginally slower.
|
| 845 |
+
_object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))
|
| 846 |
+
|
| 847 |
+
if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
|
| 848 |
+
_object_setattr(m, '__pydantic_private__', None)
|
| 849 |
+
else:
|
| 850 |
+
_object_setattr(
|
| 851 |
+
m,
|
| 852 |
+
'__pydantic_private__',
|
| 853 |
+
deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
|
| 854 |
+
)
|
| 855 |
+
|
| 856 |
+
return m
|
| 857 |
+
|
| 858 |
+
if not TYPE_CHECKING:
|
| 859 |
+
# We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access
|
| 860 |
+
# The same goes for __setattr__ and __delattr__, see: https://github.com/pydantic/pydantic/issues/8643
|
| 861 |
+
|
| 862 |
+
def __getattr__(self, item: str) -> Any:
|
| 863 |
+
private_attributes = object.__getattribute__(self, '__private_attributes__')
|
| 864 |
+
if item in private_attributes:
|
| 865 |
+
attribute = private_attributes[item]
|
| 866 |
+
if hasattr(attribute, '__get__'):
|
| 867 |
+
return attribute.__get__(self, type(self)) # type: ignore
|
| 868 |
+
|
| 869 |
+
try:
|
| 870 |
+
# Note: self.__pydantic_private__ cannot be None if self.__private_attributes__ has items
|
| 871 |
+
return self.__pydantic_private__[item] # type: ignore
|
| 872 |
+
except KeyError as exc:
|
| 873 |
+
raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') from exc
|
| 874 |
+
else:
|
| 875 |
+
# `__pydantic_extra__` can fail to be set if the model is not yet fully initialized.
|
| 876 |
+
# See `BaseModel.__repr_args__` for more details
|
| 877 |
+
try:
|
| 878 |
+
pydantic_extra = object.__getattribute__(self, '__pydantic_extra__')
|
| 879 |
+
except AttributeError:
|
| 880 |
+
pydantic_extra = None
|
| 881 |
+
|
| 882 |
+
if pydantic_extra:
|
| 883 |
+
try:
|
| 884 |
+
return pydantic_extra[item]
|
| 885 |
+
except KeyError as exc:
|
| 886 |
+
raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') from exc
|
| 887 |
+
else:
|
| 888 |
+
if hasattr(self.__class__, item):
|
| 889 |
+
return super().__getattribute__(item) # Raises AttributeError if appropriate
|
| 890 |
+
else:
|
| 891 |
+
# this is the current error
|
| 892 |
+
raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')
|
| 893 |
+
|
| 894 |
+
def __setattr__(self, name: str, value: Any) -> None:
|
| 895 |
+
if name in self.__class_vars__:
|
| 896 |
+
raise AttributeError(
|
| 897 |
+
f'{name!r} is a ClassVar of `{self.__class__.__name__}` and cannot be set on an instance. '
|
| 898 |
+
f'If you want to set a value on the class, use `{self.__class__.__name__}.{name} = value`.'
|
| 899 |
+
)
|
| 900 |
+
elif not _fields.is_valid_field_name(name):
|
| 901 |
+
if self.__pydantic_private__ is None or name not in self.__private_attributes__:
|
| 902 |
+
_object_setattr(self, name, value)
|
| 903 |
+
else:
|
| 904 |
+
attribute = self.__private_attributes__[name]
|
| 905 |
+
if hasattr(attribute, '__set__'):
|
| 906 |
+
attribute.__set__(self, value) # type: ignore
|
| 907 |
+
else:
|
| 908 |
+
self.__pydantic_private__[name] = value
|
| 909 |
+
return
|
| 910 |
+
|
| 911 |
+
self._check_frozen(name, value)
|
| 912 |
+
|
| 913 |
+
attr = getattr(self.__class__, name, None)
|
| 914 |
+
# NOTE: We currently special case properties and `cached_property`, but we might need
|
| 915 |
+
# to generalize this to all data/non-data descriptors at some point. For non-data descriptors
|
| 916 |
+
# (such as `cached_property`), it isn't obvious though. `cached_property` caches the value
|
| 917 |
+
# to the instance's `__dict__`, but other non-data descriptors might do things differently.
|
| 918 |
+
if isinstance(attr, property):
|
| 919 |
+
attr.__set__(self, value)
|
| 920 |
+
elif isinstance(attr, cached_property):
|
| 921 |
+
self.__dict__[name] = value
|
| 922 |
+
elif self.model_config.get('validate_assignment', None):
|
| 923 |
+
self.__pydantic_validator__.validate_assignment(self, name, value)
|
| 924 |
+
elif self.model_config.get('extra') != 'allow' and name not in self.__pydantic_fields__:
|
| 925 |
+
# TODO - matching error
|
| 926 |
+
raise ValueError(f'"{self.__class__.__name__}" object has no field "{name}"')
|
| 927 |
+
elif self.model_config.get('extra') == 'allow' and name not in self.__pydantic_fields__:
|
| 928 |
+
if self.model_extra and name in self.model_extra:
|
| 929 |
+
self.__pydantic_extra__[name] = value # type: ignore
|
| 930 |
+
else:
|
| 931 |
+
try:
|
| 932 |
+
getattr(self, name)
|
| 933 |
+
except AttributeError:
|
| 934 |
+
# attribute does not already exist on instance, so put it in extra
|
| 935 |
+
self.__pydantic_extra__[name] = value # type: ignore
|
| 936 |
+
else:
|
| 937 |
+
# attribute _does_ already exist on instance, and was not in extra, so update it
|
| 938 |
+
_object_setattr(self, name, value)
|
| 939 |
+
else:
|
| 940 |
+
self.__dict__[name] = value
|
| 941 |
+
self.__pydantic_fields_set__.add(name)
|
| 942 |
+
|
| 943 |
+
def __delattr__(self, item: str) -> Any:
|
| 944 |
+
if item in self.__private_attributes__:
|
| 945 |
+
attribute = self.__private_attributes__[item]
|
| 946 |
+
if hasattr(attribute, '__delete__'):
|
| 947 |
+
attribute.__delete__(self) # type: ignore
|
| 948 |
+
return
|
| 949 |
+
|
| 950 |
+
try:
|
| 951 |
+
# Note: self.__pydantic_private__ cannot be None if self.__private_attributes__ has items
|
| 952 |
+
del self.__pydantic_private__[item] # type: ignore
|
| 953 |
+
return
|
| 954 |
+
except KeyError as exc:
|
| 955 |
+
raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') from exc
|
| 956 |
+
|
| 957 |
+
self._check_frozen(item, None)
|
| 958 |
+
|
| 959 |
+
if item in self.__pydantic_fields__:
|
| 960 |
+
object.__delattr__(self, item)
|
| 961 |
+
elif self.__pydantic_extra__ is not None and item in self.__pydantic_extra__:
|
| 962 |
+
del self.__pydantic_extra__[item]
|
| 963 |
+
else:
|
| 964 |
+
try:
|
| 965 |
+
object.__delattr__(self, item)
|
| 966 |
+
except AttributeError:
|
| 967 |
+
raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')
|
| 968 |
+
|
| 969 |
+
# Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
|
| 970 |
+
# type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| 971 |
+
def __replace__(self, **changes: Any) -> Self:
|
| 972 |
+
return self.model_copy(update=changes)
|
| 973 |
+
|
| 974 |
+
def _check_frozen(self, name: str, value: Any) -> None:
|
| 975 |
+
if self.model_config.get('frozen', None):
|
| 976 |
+
typ = 'frozen_instance'
|
| 977 |
+
elif getattr(self.__pydantic_fields__.get(name), 'frozen', False):
|
| 978 |
+
typ = 'frozen_field'
|
| 979 |
+
else:
|
| 980 |
+
return
|
| 981 |
+
error: pydantic_core.InitErrorDetails = {
|
| 982 |
+
'type': typ,
|
| 983 |
+
'loc': (name,),
|
| 984 |
+
'input': value,
|
| 985 |
+
}
|
| 986 |
+
raise pydantic_core.ValidationError.from_exception_data(self.__class__.__name__, [error])
|
| 987 |
+
|
| 988 |
+
def __getstate__(self) -> dict[Any, Any]:
|
| 989 |
+
private = self.__pydantic_private__
|
| 990 |
+
if private:
|
| 991 |
+
private = {k: v for k, v in private.items() if v is not PydanticUndefined}
|
| 992 |
+
return {
|
| 993 |
+
'__dict__': self.__dict__,
|
| 994 |
+
'__pydantic_extra__': self.__pydantic_extra__,
|
| 995 |
+
'__pydantic_fields_set__': self.__pydantic_fields_set__,
|
| 996 |
+
'__pydantic_private__': private,
|
| 997 |
+
}
|
| 998 |
+
|
| 999 |
+
def __setstate__(self, state: dict[Any, Any]) -> None:
|
| 1000 |
+
_object_setattr(self, '__pydantic_fields_set__', state.get('__pydantic_fields_set__', {}))
|
| 1001 |
+
_object_setattr(self, '__pydantic_extra__', state.get('__pydantic_extra__', {}))
|
| 1002 |
+
_object_setattr(self, '__pydantic_private__', state.get('__pydantic_private__', {}))
|
| 1003 |
+
_object_setattr(self, '__dict__', state.get('__dict__', {}))
|
| 1004 |
+
|
| 1005 |
+
if not TYPE_CHECKING:
|
| 1006 |
+
|
| 1007 |
+
def __eq__(self, other: Any) -> bool:
|
| 1008 |
+
if isinstance(other, BaseModel):
|
| 1009 |
+
# When comparing instances of generic types for equality, as long as all field values are equal,
|
| 1010 |
+
# only require their generic origin types to be equal, rather than exact type equality.
|
| 1011 |
+
# This prevents headaches like MyGeneric(x=1) != MyGeneric[Any](x=1).
|
| 1012 |
+
self_type = self.__pydantic_generic_metadata__['origin'] or self.__class__
|
| 1013 |
+
other_type = other.__pydantic_generic_metadata__['origin'] or other.__class__
|
| 1014 |
+
|
| 1015 |
+
# Perform common checks first
|
| 1016 |
+
if not (
|
| 1017 |
+
self_type == other_type
|
| 1018 |
+
and getattr(self, '__pydantic_private__', None) == getattr(other, '__pydantic_private__', None)
|
| 1019 |
+
and self.__pydantic_extra__ == other.__pydantic_extra__
|
| 1020 |
+
):
|
| 1021 |
+
return False
|
| 1022 |
+
|
| 1023 |
+
# We only want to compare pydantic fields but ignoring fields is costly.
|
| 1024 |
+
# We'll perform a fast check first, and fallback only when needed
|
| 1025 |
+
# See GH-7444 and GH-7825 for rationale and a performance benchmark
|
| 1026 |
+
|
| 1027 |
+
# First, do the fast (and sometimes faulty) __dict__ comparison
|
| 1028 |
+
if self.__dict__ == other.__dict__:
|
| 1029 |
+
# If the check above passes, then pydantic fields are equal, we can return early
|
| 1030 |
+
return True
|
| 1031 |
+
|
| 1032 |
+
# We don't want to trigger unnecessary costly filtering of __dict__ on all unequal objects, so we return
|
| 1033 |
+
# early if there are no keys to ignore (we would just return False later on anyway)
|
| 1034 |
+
model_fields = type(self).__pydantic_fields__.keys()
|
| 1035 |
+
if self.__dict__.keys() <= model_fields and other.__dict__.keys() <= model_fields:
|
| 1036 |
+
return False
|
| 1037 |
+
|
| 1038 |
+
# If we reach here, there are non-pydantic-fields keys, mapped to unequal values, that we need to ignore
|
| 1039 |
+
# Resort to costly filtering of the __dict__ objects
|
| 1040 |
+
# We use operator.itemgetter because it is much faster than dict comprehensions
|
| 1041 |
+
# NOTE: Contrary to standard python class and instances, when the Model class has a default value for an
|
| 1042 |
+
# attribute and the model instance doesn't have a corresponding attribute, accessing the missing attribute
|
| 1043 |
+
# raises an error in BaseModel.__getattr__ instead of returning the class attribute
|
| 1044 |
+
# So we can use operator.itemgetter() instead of operator.attrgetter()
|
| 1045 |
+
getter = operator.itemgetter(*model_fields) if model_fields else lambda _: _utils._SENTINEL
|
| 1046 |
+
try:
|
| 1047 |
+
return getter(self.__dict__) == getter(other.__dict__)
|
| 1048 |
+
except KeyError:
|
| 1049 |
+
# In rare cases (such as when using the deprecated BaseModel.copy() method),
|
| 1050 |
+
# the __dict__ may not contain all model fields, which is how we can get here.
|
| 1051 |
+
# getter(self.__dict__) is much faster than any 'safe' method that accounts
|
| 1052 |
+
# for missing keys, and wrapping it in a `try` doesn't slow things down much
|
| 1053 |
+
# in the common case.
|
| 1054 |
+
self_fields_proxy = _utils.SafeGetItemProxy(self.__dict__)
|
| 1055 |
+
other_fields_proxy = _utils.SafeGetItemProxy(other.__dict__)
|
| 1056 |
+
return getter(self_fields_proxy) == getter(other_fields_proxy)
|
| 1057 |
+
|
| 1058 |
+
# other instance is not a BaseModel
|
| 1059 |
+
else:
|
| 1060 |
+
return NotImplemented # delegate to the other item in the comparison
|
| 1061 |
+
|
| 1062 |
+
if TYPE_CHECKING:
|
| 1063 |
+
# We put `__init_subclass__` in a TYPE_CHECKING block because, even though we want the type-checking benefits
|
| 1064 |
+
# described in the signature of `__init_subclass__` below, we don't want to modify the default behavior of
|
| 1065 |
+
# subclass initialization.
|
| 1066 |
+
|
| 1067 |
+
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
|
| 1068 |
+
"""This signature is included purely to help type-checkers check arguments to class declaration, which
|
| 1069 |
+
provides a way to conveniently set model_config key/value pairs.
|
| 1070 |
+
|
| 1071 |
+
```python
|
| 1072 |
+
from pydantic import BaseModel
|
| 1073 |
+
|
| 1074 |
+
class MyModel(BaseModel, extra='allow'): ...
|
| 1075 |
+
```
|
| 1076 |
+
|
| 1077 |
+
However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
|
| 1078 |
+
of the config arguments, and will only receive any keyword arguments passed during class initialization
|
| 1079 |
+
that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)
|
| 1080 |
+
|
| 1081 |
+
Args:
|
| 1082 |
+
**kwargs: Keyword arguments passed to the class definition, which set model_config
|
| 1083 |
+
|
| 1084 |
+
Note:
|
| 1085 |
+
You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
|
| 1086 |
+
*after* the class is fully initialized.
|
| 1087 |
+
"""
|
| 1088 |
+
|
| 1089 |
+
def __iter__(self) -> TupleGenerator:
|
| 1090 |
+
"""So `dict(model)` works."""
|
| 1091 |
+
yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
|
| 1092 |
+
extra = self.__pydantic_extra__
|
| 1093 |
+
if extra:
|
| 1094 |
+
yield from extra.items()
|
| 1095 |
+
|
| 1096 |
+
def __repr__(self) -> str:
|
| 1097 |
+
return f'{self.__repr_name__()}({self.__repr_str__(", ")})'
|
| 1098 |
+
|
| 1099 |
+
def __repr_args__(self) -> _repr.ReprArgs:
|
| 1100 |
+
for k, v in self.__dict__.items():
|
| 1101 |
+
field = self.__pydantic_fields__.get(k)
|
| 1102 |
+
if field and field.repr:
|
| 1103 |
+
if v is not self:
|
| 1104 |
+
yield k, v
|
| 1105 |
+
else:
|
| 1106 |
+
yield k, self.__repr_recursion__(v)
|
| 1107 |
+
# `__pydantic_extra__` can fail to be set if the model is not yet fully initialized.
|
| 1108 |
+
# This can happen if a `ValidationError` is raised during initialization and the instance's
|
| 1109 |
+
# repr is generated as part of the exception handling. Therefore, we use `getattr` here
|
| 1110 |
+
# with a fallback, even though the type hints indicate the attribute will always be present.
|
| 1111 |
+
try:
|
| 1112 |
+
pydantic_extra = object.__getattribute__(self, '__pydantic_extra__')
|
| 1113 |
+
except AttributeError:
|
| 1114 |
+
pydantic_extra = None
|
| 1115 |
+
|
| 1116 |
+
if pydantic_extra is not None:
|
| 1117 |
+
yield from ((k, v) for k, v in pydantic_extra.items())
|
| 1118 |
+
yield from ((k, getattr(self, k)) for k, v in self.__pydantic_computed_fields__.items() if v.repr)
|
| 1119 |
+
|
| 1120 |
+
# take logic from `_repr.Representation` without the side effects of inheritance, see #5740
|
| 1121 |
+
__repr_name__ = _repr.Representation.__repr_name__
|
| 1122 |
+
__repr_recursion__ = _repr.Representation.__repr_recursion__
|
| 1123 |
+
__repr_str__ = _repr.Representation.__repr_str__
|
| 1124 |
+
__pretty__ = _repr.Representation.__pretty__
|
| 1125 |
+
__rich_repr__ = _repr.Representation.__rich_repr__
|
| 1126 |
+
|
| 1127 |
+
def __str__(self) -> str:
|
| 1128 |
+
return self.__repr_str__(' ')
|
| 1129 |
+
|
| 1130 |
+
# ##### Deprecated methods from v1 #####
|
| 1131 |
+
@property
|
| 1132 |
+
@typing_extensions.deprecated(
|
| 1133 |
+
'The `__fields__` attribute is deprecated, use `model_fields` instead.', category=None
|
| 1134 |
+
)
|
| 1135 |
+
def __fields__(self) -> dict[str, FieldInfo]:
|
| 1136 |
+
warnings.warn(
|
| 1137 |
+
'The `__fields__` attribute is deprecated, use `model_fields` instead.',
|
| 1138 |
+
category=PydanticDeprecatedSince20,
|
| 1139 |
+
stacklevel=2,
|
| 1140 |
+
)
|
| 1141 |
+
return self.model_fields
|
| 1142 |
+
|
| 1143 |
+
@property
|
| 1144 |
+
@typing_extensions.deprecated(
|
| 1145 |
+
'The `__fields_set__` attribute is deprecated, use `model_fields_set` instead.',
|
| 1146 |
+
category=None,
|
| 1147 |
+
)
|
| 1148 |
+
def __fields_set__(self) -> set[str]:
|
| 1149 |
+
warnings.warn(
|
| 1150 |
+
'The `__fields_set__` attribute is deprecated, use `model_fields_set` instead.',
|
| 1151 |
+
category=PydanticDeprecatedSince20,
|
| 1152 |
+
stacklevel=2,
|
| 1153 |
+
)
|
| 1154 |
+
return self.__pydantic_fields_set__
|
| 1155 |
+
|
| 1156 |
+
@typing_extensions.deprecated('The `dict` method is deprecated; use `model_dump` instead.', category=None)
|
| 1157 |
+
def dict( # noqa: D102
|
| 1158 |
+
self,
|
| 1159 |
+
*,
|
| 1160 |
+
include: IncEx | None = None,
|
| 1161 |
+
exclude: IncEx | None = None,
|
| 1162 |
+
by_alias: bool = False,
|
| 1163 |
+
exclude_unset: bool = False,
|
| 1164 |
+
exclude_defaults: bool = False,
|
| 1165 |
+
exclude_none: bool = False,
|
| 1166 |
+
) -> Dict[str, Any]: # noqa UP006
|
| 1167 |
+
warnings.warn(
|
| 1168 |
+
'The `dict` method is deprecated; use `model_dump` instead.',
|
| 1169 |
+
category=PydanticDeprecatedSince20,
|
| 1170 |
+
stacklevel=2,
|
| 1171 |
+
)
|
| 1172 |
+
return self.model_dump(
|
| 1173 |
+
include=include,
|
| 1174 |
+
exclude=exclude,
|
| 1175 |
+
by_alias=by_alias,
|
| 1176 |
+
exclude_unset=exclude_unset,
|
| 1177 |
+
exclude_defaults=exclude_defaults,
|
| 1178 |
+
exclude_none=exclude_none,
|
| 1179 |
+
)
|
| 1180 |
+
|
| 1181 |
+
@typing_extensions.deprecated('The `json` method is deprecated; use `model_dump_json` instead.', category=None)
|
| 1182 |
+
def json( # noqa: D102
|
| 1183 |
+
self,
|
| 1184 |
+
*,
|
| 1185 |
+
include: IncEx | None = None,
|
| 1186 |
+
exclude: IncEx | None = None,
|
| 1187 |
+
by_alias: bool = False,
|
| 1188 |
+
exclude_unset: bool = False,
|
| 1189 |
+
exclude_defaults: bool = False,
|
| 1190 |
+
exclude_none: bool = False,
|
| 1191 |
+
encoder: Callable[[Any], Any] | None = PydanticUndefined, # type: ignore[assignment]
|
| 1192 |
+
models_as_dict: bool = PydanticUndefined, # type: ignore[assignment]
|
| 1193 |
+
**dumps_kwargs: Any,
|
| 1194 |
+
) -> str:
|
| 1195 |
+
warnings.warn(
|
| 1196 |
+
'The `json` method is deprecated; use `model_dump_json` instead.',
|
| 1197 |
+
category=PydanticDeprecatedSince20,
|
| 1198 |
+
stacklevel=2,
|
| 1199 |
+
)
|
| 1200 |
+
if encoder is not PydanticUndefined:
|
| 1201 |
+
raise TypeError('The `encoder` argument is no longer supported; use field serializers instead.')
|
| 1202 |
+
if models_as_dict is not PydanticUndefined:
|
| 1203 |
+
raise TypeError('The `models_as_dict` argument is no longer supported; use a model serializer instead.')
|
| 1204 |
+
if dumps_kwargs:
|
| 1205 |
+
raise TypeError('`dumps_kwargs` keyword arguments are no longer supported.')
|
| 1206 |
+
return self.model_dump_json(
|
| 1207 |
+
include=include,
|
| 1208 |
+
exclude=exclude,
|
| 1209 |
+
by_alias=by_alias,
|
| 1210 |
+
exclude_unset=exclude_unset,
|
| 1211 |
+
exclude_defaults=exclude_defaults,
|
| 1212 |
+
exclude_none=exclude_none,
|
| 1213 |
+
)
|
| 1214 |
+
|
| 1215 |
+
@classmethod
|
| 1216 |
+
@typing_extensions.deprecated('The `parse_obj` method is deprecated; use `model_validate` instead.', category=None)
|
| 1217 |
+
def parse_obj(cls, obj: Any) -> Self: # noqa: D102
|
| 1218 |
+
warnings.warn(
|
| 1219 |
+
'The `parse_obj` method is deprecated; use `model_validate` instead.',
|
| 1220 |
+
category=PydanticDeprecatedSince20,
|
| 1221 |
+
stacklevel=2,
|
| 1222 |
+
)
|
| 1223 |
+
return cls.model_validate(obj)
|
| 1224 |
+
|
| 1225 |
+
@classmethod
|
| 1226 |
+
@typing_extensions.deprecated(
|
| 1227 |
+
'The `parse_raw` method is deprecated; if your data is JSON use `model_validate_json`, '
|
| 1228 |
+
'otherwise load the data then use `model_validate` instead.',
|
| 1229 |
+
category=None,
|
| 1230 |
+
)
|
| 1231 |
+
def parse_raw( # noqa: D102
|
| 1232 |
+
cls,
|
| 1233 |
+
b: str | bytes,
|
| 1234 |
+
*,
|
| 1235 |
+
content_type: str | None = None,
|
| 1236 |
+
encoding: str = 'utf8',
|
| 1237 |
+
proto: DeprecatedParseProtocol | None = None,
|
| 1238 |
+
allow_pickle: bool = False,
|
| 1239 |
+
) -> Self: # pragma: no cover
|
| 1240 |
+
warnings.warn(
|
| 1241 |
+
'The `parse_raw` method is deprecated; if your data is JSON use `model_validate_json`, '
|
| 1242 |
+
'otherwise load the data then use `model_validate` instead.',
|
| 1243 |
+
category=PydanticDeprecatedSince20,
|
| 1244 |
+
stacklevel=2,
|
| 1245 |
+
)
|
| 1246 |
+
from .deprecated import parse
|
| 1247 |
+
|
| 1248 |
+
try:
|
| 1249 |
+
obj = parse.load_str_bytes(
|
| 1250 |
+
b,
|
| 1251 |
+
proto=proto,
|
| 1252 |
+
content_type=content_type,
|
| 1253 |
+
encoding=encoding,
|
| 1254 |
+
allow_pickle=allow_pickle,
|
| 1255 |
+
)
|
| 1256 |
+
except (ValueError, TypeError) as exc:
|
| 1257 |
+
import json
|
| 1258 |
+
|
| 1259 |
+
# try to match V1
|
| 1260 |
+
if isinstance(exc, UnicodeDecodeError):
|
| 1261 |
+
type_str = 'value_error.unicodedecode'
|
| 1262 |
+
elif isinstance(exc, json.JSONDecodeError):
|
| 1263 |
+
type_str = 'value_error.jsondecode'
|
| 1264 |
+
elif isinstance(exc, ValueError):
|
| 1265 |
+
type_str = 'value_error'
|
| 1266 |
+
else:
|
| 1267 |
+
type_str = 'type_error'
|
| 1268 |
+
|
| 1269 |
+
# ctx is missing here, but since we've added `input` to the error, we're not pretending it's the same
|
| 1270 |
+
error: pydantic_core.InitErrorDetails = {
|
| 1271 |
+
# The type: ignore on the next line is to ignore the requirement of LiteralString
|
| 1272 |
+
'type': pydantic_core.PydanticCustomError(type_str, str(exc)), # type: ignore
|
| 1273 |
+
'loc': ('__root__',),
|
| 1274 |
+
'input': b,
|
| 1275 |
+
}
|
| 1276 |
+
raise pydantic_core.ValidationError.from_exception_data(cls.__name__, [error])
|
| 1277 |
+
return cls.model_validate(obj)
|
| 1278 |
+
|
| 1279 |
+
@classmethod
|
| 1280 |
+
@typing_extensions.deprecated(
|
| 1281 |
+
'The `parse_file` method is deprecated; load the data from file, then if your data is JSON '
|
| 1282 |
+
'use `model_validate_json`, otherwise `model_validate` instead.',
|
| 1283 |
+
category=None,
|
| 1284 |
+
)
|
| 1285 |
+
def parse_file( # noqa: D102
|
| 1286 |
+
cls,
|
| 1287 |
+
path: str | Path,
|
| 1288 |
+
*,
|
| 1289 |
+
content_type: str | None = None,
|
| 1290 |
+
encoding: str = 'utf8',
|
| 1291 |
+
proto: DeprecatedParseProtocol | None = None,
|
| 1292 |
+
allow_pickle: bool = False,
|
| 1293 |
+
) -> Self:
|
| 1294 |
+
warnings.warn(
|
| 1295 |
+
'The `parse_file` method is deprecated; load the data from file, then if your data is JSON '
|
| 1296 |
+
'use `model_validate_json`, otherwise `model_validate` instead.',
|
| 1297 |
+
category=PydanticDeprecatedSince20,
|
| 1298 |
+
stacklevel=2,
|
| 1299 |
+
)
|
| 1300 |
+
from .deprecated import parse
|
| 1301 |
+
|
| 1302 |
+
obj = parse.load_file(
|
| 1303 |
+
path,
|
| 1304 |
+
proto=proto,
|
| 1305 |
+
content_type=content_type,
|
| 1306 |
+
encoding=encoding,
|
| 1307 |
+
allow_pickle=allow_pickle,
|
| 1308 |
+
)
|
| 1309 |
+
return cls.parse_obj(obj)
|
| 1310 |
+
|
| 1311 |
+
@classmethod
|
| 1312 |
+
@typing_extensions.deprecated(
|
| 1313 |
+
'The `from_orm` method is deprecated; set '
|
| 1314 |
+
"`model_config['from_attributes']=True` and use `model_validate` instead.",
|
| 1315 |
+
category=None,
|
| 1316 |
+
)
|
| 1317 |
+
def from_orm(cls, obj: Any) -> Self: # noqa: D102
|
| 1318 |
+
warnings.warn(
|
| 1319 |
+
'The `from_orm` method is deprecated; set '
|
| 1320 |
+
"`model_config['from_attributes']=True` and use `model_validate` instead.",
|
| 1321 |
+
category=PydanticDeprecatedSince20,
|
| 1322 |
+
stacklevel=2,
|
| 1323 |
+
)
|
| 1324 |
+
if not cls.model_config.get('from_attributes', None):
|
| 1325 |
+
raise PydanticUserError(
|
| 1326 |
+
'You must set the config attribute `from_attributes=True` to use from_orm', code=None
|
| 1327 |
+
)
|
| 1328 |
+
return cls.model_validate(obj)
|
| 1329 |
+
|
| 1330 |
+
@classmethod
|
| 1331 |
+
@typing_extensions.deprecated('The `construct` method is deprecated; use `model_construct` instead.', category=None)
|
| 1332 |
+
def construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self: # noqa: D102
|
| 1333 |
+
warnings.warn(
|
| 1334 |
+
'The `construct` method is deprecated; use `model_construct` instead.',
|
| 1335 |
+
category=PydanticDeprecatedSince20,
|
| 1336 |
+
stacklevel=2,
|
| 1337 |
+
)
|
| 1338 |
+
return cls.model_construct(_fields_set=_fields_set, **values)
|
| 1339 |
+
|
| 1340 |
+
@typing_extensions.deprecated(
|
| 1341 |
+
'The `copy` method is deprecated; use `model_copy` instead. '
|
| 1342 |
+
'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
|
| 1343 |
+
category=None,
|
| 1344 |
+
)
|
| 1345 |
+
def copy(
|
| 1346 |
+
self,
|
| 1347 |
+
*,
|
| 1348 |
+
include: AbstractSetIntStr | MappingIntStrAny | None = None,
|
| 1349 |
+
exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
|
| 1350 |
+
update: Dict[str, Any] | None = None, # noqa UP006
|
| 1351 |
+
deep: bool = False,
|
| 1352 |
+
) -> Self: # pragma: no cover
|
| 1353 |
+
"""Returns a copy of the model.
|
| 1354 |
+
|
| 1355 |
+
!!! warning "Deprecated"
|
| 1356 |
+
This method is now deprecated; use `model_copy` instead.
|
| 1357 |
+
|
| 1358 |
+
If you need `include` or `exclude`, use:
|
| 1359 |
+
|
| 1360 |
+
```python {test="skip" lint="skip"}
|
| 1361 |
+
data = self.model_dump(include=include, exclude=exclude, round_trip=True)
|
| 1362 |
+
data = {**data, **(update or {})}
|
| 1363 |
+
copied = self.model_validate(data)
|
| 1364 |
+
```
|
| 1365 |
+
|
| 1366 |
+
Args:
|
| 1367 |
+
include: Optional set or mapping specifying which fields to include in the copied model.
|
| 1368 |
+
exclude: Optional set or mapping specifying which fields to exclude in the copied model.
|
| 1369 |
+
update: Optional dictionary of field-value pairs to override field values in the copied model.
|
| 1370 |
+
deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| 1371 |
+
|
| 1372 |
+
Returns:
|
| 1373 |
+
A copy of the model with included, excluded and updated fields as specified.
|
| 1374 |
+
"""
|
| 1375 |
+
warnings.warn(
|
| 1376 |
+
'The `copy` method is deprecated; use `model_copy` instead. '
|
| 1377 |
+
'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
|
| 1378 |
+
category=PydanticDeprecatedSince20,
|
| 1379 |
+
stacklevel=2,
|
| 1380 |
+
)
|
| 1381 |
+
from .deprecated import copy_internals
|
| 1382 |
+
|
| 1383 |
+
values = dict(
|
| 1384 |
+
copy_internals._iter(
|
| 1385 |
+
self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
|
| 1386 |
+
),
|
| 1387 |
+
**(update or {}),
|
| 1388 |
+
)
|
| 1389 |
+
if self.__pydantic_private__ is None:
|
| 1390 |
+
private = None
|
| 1391 |
+
else:
|
| 1392 |
+
private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}
|
| 1393 |
+
|
| 1394 |
+
if self.__pydantic_extra__ is None:
|
| 1395 |
+
extra: dict[str, Any] | None = None
|
| 1396 |
+
else:
|
| 1397 |
+
extra = self.__pydantic_extra__.copy()
|
| 1398 |
+
for k in list(self.__pydantic_extra__):
|
| 1399 |
+
if k not in values: # k was in the exclude
|
| 1400 |
+
extra.pop(k)
|
| 1401 |
+
for k in list(values):
|
| 1402 |
+
if k in self.__pydantic_extra__: # k must have come from extra
|
| 1403 |
+
extra[k] = values.pop(k)
|
| 1404 |
+
|
| 1405 |
+
# new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
|
| 1406 |
+
if update:
|
| 1407 |
+
fields_set = self.__pydantic_fields_set__ | update.keys()
|
| 1408 |
+
else:
|
| 1409 |
+
fields_set = set(self.__pydantic_fields_set__)
|
| 1410 |
+
|
| 1411 |
+
# removing excluded fields from `__pydantic_fields_set__`
|
| 1412 |
+
if exclude:
|
| 1413 |
+
fields_set -= set(exclude)
|
| 1414 |
+
|
| 1415 |
+
return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)
|
| 1416 |
+
|
| 1417 |
+
@classmethod
|
| 1418 |
+
@typing_extensions.deprecated('The `schema` method is deprecated; use `model_json_schema` instead.', category=None)
|
| 1419 |
+
def schema( # noqa: D102
|
| 1420 |
+
cls, by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE
|
| 1421 |
+
) -> Dict[str, Any]: # noqa UP006
|
| 1422 |
+
warnings.warn(
|
| 1423 |
+
'The `schema` method is deprecated; use `model_json_schema` instead.',
|
| 1424 |
+
category=PydanticDeprecatedSince20,
|
| 1425 |
+
stacklevel=2,
|
| 1426 |
+
)
|
| 1427 |
+
return cls.model_json_schema(by_alias=by_alias, ref_template=ref_template)
|
| 1428 |
+
|
| 1429 |
+
@classmethod
|
| 1430 |
+
@typing_extensions.deprecated(
|
| 1431 |
+
'The `schema_json` method is deprecated; use `model_json_schema` and json.dumps instead.',
|
| 1432 |
+
category=None,
|
| 1433 |
+
)
|
| 1434 |
+
def schema_json( # noqa: D102
|
| 1435 |
+
cls, *, by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE, **dumps_kwargs: Any
|
| 1436 |
+
) -> str: # pragma: no cover
|
| 1437 |
+
warnings.warn(
|
| 1438 |
+
'The `schema_json` method is deprecated; use `model_json_schema` and json.dumps instead.',
|
| 1439 |
+
category=PydanticDeprecatedSince20,
|
| 1440 |
+
stacklevel=2,
|
| 1441 |
+
)
|
| 1442 |
+
import json
|
| 1443 |
+
|
| 1444 |
+
from .deprecated.json import pydantic_encoder
|
| 1445 |
+
|
| 1446 |
+
return json.dumps(
|
| 1447 |
+
cls.model_json_schema(by_alias=by_alias, ref_template=ref_template),
|
| 1448 |
+
default=pydantic_encoder,
|
| 1449 |
+
**dumps_kwargs,
|
| 1450 |
+
)
|
| 1451 |
+
|
| 1452 |
+
@classmethod
|
| 1453 |
+
@typing_extensions.deprecated('The `validate` method is deprecated; use `model_validate` instead.', category=None)
|
| 1454 |
+
def validate(cls, value: Any) -> Self: # noqa: D102
|
| 1455 |
+
warnings.warn(
|
| 1456 |
+
'The `validate` method is deprecated; use `model_validate` instead.',
|
| 1457 |
+
category=PydanticDeprecatedSince20,
|
| 1458 |
+
stacklevel=2,
|
| 1459 |
+
)
|
| 1460 |
+
return cls.model_validate(value)
|
| 1461 |
+
|
| 1462 |
+
@classmethod
|
| 1463 |
+
@typing_extensions.deprecated(
|
| 1464 |
+
'The `update_forward_refs` method is deprecated; use `model_rebuild` instead.',
|
| 1465 |
+
category=None,
|
| 1466 |
+
)
|
| 1467 |
+
def update_forward_refs(cls, **localns: Any) -> None: # noqa: D102
|
| 1468 |
+
warnings.warn(
|
| 1469 |
+
'The `update_forward_refs` method is deprecated; use `model_rebuild` instead.',
|
| 1470 |
+
category=PydanticDeprecatedSince20,
|
| 1471 |
+
stacklevel=2,
|
| 1472 |
+
)
|
| 1473 |
+
if localns: # pragma: no cover
|
| 1474 |
+
raise TypeError('`localns` arguments are not longer accepted.')
|
| 1475 |
+
cls.model_rebuild(force=True)
|
| 1476 |
+
|
| 1477 |
+
@typing_extensions.deprecated(
|
| 1478 |
+
'The private method `_iter` will be removed and should no longer be used.', category=None
|
| 1479 |
+
)
|
| 1480 |
+
def _iter(self, *args: Any, **kwargs: Any) -> Any:
|
| 1481 |
+
warnings.warn(
|
| 1482 |
+
'The private method `_iter` will be removed and should no longer be used.',
|
| 1483 |
+
category=PydanticDeprecatedSince20,
|
| 1484 |
+
stacklevel=2,
|
| 1485 |
+
)
|
| 1486 |
+
from .deprecated import copy_internals
|
| 1487 |
+
|
| 1488 |
+
return copy_internals._iter(self, *args, **kwargs)
|
| 1489 |
+
|
| 1490 |
+
@typing_extensions.deprecated(
|
| 1491 |
+
'The private method `_copy_and_set_values` will be removed and should no longer be used.',
|
| 1492 |
+
category=None,
|
| 1493 |
+
)
|
| 1494 |
+
def _copy_and_set_values(self, *args: Any, **kwargs: Any) -> Any:
|
| 1495 |
+
warnings.warn(
|
| 1496 |
+
'The private method `_copy_and_set_values` will be removed and should no longer be used.',
|
| 1497 |
+
category=PydanticDeprecatedSince20,
|
| 1498 |
+
stacklevel=2,
|
| 1499 |
+
)
|
| 1500 |
+
from .deprecated import copy_internals
|
| 1501 |
+
|
| 1502 |
+
return copy_internals._copy_and_set_values(self, *args, **kwargs)
|
| 1503 |
+
|
| 1504 |
+
@classmethod
|
| 1505 |
+
@typing_extensions.deprecated(
|
| 1506 |
+
'The private method `_get_value` will be removed and should no longer be used.',
|
| 1507 |
+
category=None,
|
| 1508 |
+
)
|
| 1509 |
+
def _get_value(cls, *args: Any, **kwargs: Any) -> Any:
|
| 1510 |
+
warnings.warn(
|
| 1511 |
+
'The private method `_get_value` will be removed and should no longer be used.',
|
| 1512 |
+
category=PydanticDeprecatedSince20,
|
| 1513 |
+
stacklevel=2,
|
| 1514 |
+
)
|
| 1515 |
+
from .deprecated import copy_internals
|
| 1516 |
+
|
| 1517 |
+
return copy_internals._get_value(cls, *args, **kwargs)
|
| 1518 |
+
|
| 1519 |
+
@typing_extensions.deprecated(
|
| 1520 |
+
'The private method `_calculate_keys` will be removed and should no longer be used.',
|
| 1521 |
+
category=None,
|
| 1522 |
+
)
|
| 1523 |
+
def _calculate_keys(self, *args: Any, **kwargs: Any) -> Any:
|
| 1524 |
+
warnings.warn(
|
| 1525 |
+
'The private method `_calculate_keys` will be removed and should no longer be used.',
|
| 1526 |
+
category=PydanticDeprecatedSince20,
|
| 1527 |
+
stacklevel=2,
|
| 1528 |
+
)
|
| 1529 |
+
from .deprecated import copy_internals
|
| 1530 |
+
|
| 1531 |
+
return copy_internals._calculate_keys(self, *args, **kwargs)
|
| 1532 |
+
|
| 1533 |
+
|
| 1534 |
+
ModelT = TypeVar('ModelT', bound=BaseModel)
|
| 1535 |
+
|
| 1536 |
+
|
| 1537 |
+
@overload
|
| 1538 |
+
def create_model(
|
| 1539 |
+
model_name: str,
|
| 1540 |
+
/,
|
| 1541 |
+
*,
|
| 1542 |
+
__config__: ConfigDict | None = None,
|
| 1543 |
+
__doc__: str | None = None,
|
| 1544 |
+
__base__: None = None,
|
| 1545 |
+
__module__: str = __name__,
|
| 1546 |
+
__validators__: dict[str, Callable[..., Any]] | None = None,
|
| 1547 |
+
__cls_kwargs__: dict[str, Any] | None = None,
|
| 1548 |
+
**field_definitions: Any,
|
| 1549 |
+
) -> type[BaseModel]: ...
|
| 1550 |
+
|
| 1551 |
+
|
| 1552 |
+
@overload
|
| 1553 |
+
def create_model(
|
| 1554 |
+
model_name: str,
|
| 1555 |
+
/,
|
| 1556 |
+
*,
|
| 1557 |
+
__config__: ConfigDict | None = None,
|
| 1558 |
+
__doc__: str | None = None,
|
| 1559 |
+
__base__: type[ModelT] | tuple[type[ModelT], ...],
|
| 1560 |
+
__module__: str = __name__,
|
| 1561 |
+
__validators__: dict[str, Callable[..., Any]] | None = None,
|
| 1562 |
+
__cls_kwargs__: dict[str, Any] | None = None,
|
| 1563 |
+
**field_definitions: Any,
|
| 1564 |
+
) -> type[ModelT]: ...
|
| 1565 |
+
|
| 1566 |
+
|
| 1567 |
+
def create_model( # noqa: C901
|
| 1568 |
+
model_name: str,
|
| 1569 |
+
/,
|
| 1570 |
+
*,
|
| 1571 |
+
__config__: ConfigDict | None = None,
|
| 1572 |
+
__doc__: str | None = None,
|
| 1573 |
+
__base__: type[ModelT] | tuple[type[ModelT], ...] | None = None,
|
| 1574 |
+
__module__: str | None = None,
|
| 1575 |
+
__validators__: dict[str, Callable[..., Any]] | None = None,
|
| 1576 |
+
__cls_kwargs__: dict[str, Any] | None = None,
|
| 1577 |
+
__slots__: tuple[str, ...] | None = None,
|
| 1578 |
+
**field_definitions: Any,
|
| 1579 |
+
) -> type[ModelT]:
|
| 1580 |
+
"""Usage docs: https://docs.pydantic.dev/2.10/concepts/models/#dynamic-model-creation
|
| 1581 |
+
|
| 1582 |
+
Dynamically creates and returns a new Pydantic model, in other words, `create_model` dynamically creates a
|
| 1583 |
+
subclass of [`BaseModel`][pydantic.BaseModel].
|
| 1584 |
+
|
| 1585 |
+
Args:
|
| 1586 |
+
model_name: The name of the newly created model.
|
| 1587 |
+
__config__: The configuration of the new model.
|
| 1588 |
+
__doc__: The docstring of the new model.
|
| 1589 |
+
__base__: The base class or classes for the new model.
|
| 1590 |
+
__module__: The name of the module that the model belongs to;
|
| 1591 |
+
if `None`, the value is taken from `sys._getframe(1)`
|
| 1592 |
+
__validators__: A dictionary of methods that validate fields. The keys are the names of the validation methods to
|
| 1593 |
+
be added to the model, and the values are the validation methods themselves. You can read more about functional
|
| 1594 |
+
validators [here](https://docs.pydantic.dev/2.9/concepts/validators/#field-validators).
|
| 1595 |
+
__cls_kwargs__: A dictionary of keyword arguments for class creation, such as `metaclass`.
|
| 1596 |
+
__slots__: Deprecated. Should not be passed to `create_model`.
|
| 1597 |
+
**field_definitions: Attributes of the new model. They should be passed in the format:
|
| 1598 |
+
`<name>=(<type>, <default value>)`, `<name>=(<type>, <FieldInfo>)`, or `typing.Annotated[<type>, <FieldInfo>]`.
|
| 1599 |
+
Any additional metadata in `typing.Annotated[<type>, <FieldInfo>, ...]` will be ignored.
|
| 1600 |
+
Note, `FieldInfo` instances should be created via `pydantic.Field(...)`.
|
| 1601 |
+
Initializing `FieldInfo` instances directly is not supported.
|
| 1602 |
+
|
| 1603 |
+
Returns:
|
| 1604 |
+
The new [model][pydantic.BaseModel].
|
| 1605 |
+
|
| 1606 |
+
Raises:
|
| 1607 |
+
PydanticUserError: If `__base__` and `__config__` are both passed.
|
| 1608 |
+
"""
|
| 1609 |
+
if __slots__ is not None:
|
| 1610 |
+
# __slots__ will be ignored from here on
|
| 1611 |
+
warnings.warn('__slots__ should not be passed to create_model', RuntimeWarning)
|
| 1612 |
+
|
| 1613 |
+
if __base__ is not None:
|
| 1614 |
+
if __config__ is not None:
|
| 1615 |
+
raise PydanticUserError(
|
| 1616 |
+
'to avoid confusion `__config__` and `__base__` cannot be used together',
|
| 1617 |
+
code='create-model-config-base',
|
| 1618 |
+
)
|
| 1619 |
+
if not isinstance(__base__, tuple):
|
| 1620 |
+
__base__ = (__base__,)
|
| 1621 |
+
else:
|
| 1622 |
+
__base__ = (cast('type[ModelT]', BaseModel),)
|
| 1623 |
+
|
| 1624 |
+
__cls_kwargs__ = __cls_kwargs__ or {}
|
| 1625 |
+
|
| 1626 |
+
fields = {}
|
| 1627 |
+
annotations = {}
|
| 1628 |
+
|
| 1629 |
+
for f_name, f_def in field_definitions.items():
|
| 1630 |
+
if not _fields.is_valid_field_name(f_name):
|
| 1631 |
+
warnings.warn(f'fields may not start with an underscore, ignoring "{f_name}"', RuntimeWarning)
|
| 1632 |
+
if isinstance(f_def, tuple):
|
| 1633 |
+
f_def = cast('tuple[str, Any]', f_def)
|
| 1634 |
+
try:
|
| 1635 |
+
f_annotation, f_value = f_def
|
| 1636 |
+
except ValueError as e:
|
| 1637 |
+
raise PydanticUserError(
|
| 1638 |
+
'Field definitions should be a `(<type>, <default>)`.',
|
| 1639 |
+
code='create-model-field-definitions',
|
| 1640 |
+
) from e
|
| 1641 |
+
|
| 1642 |
+
elif _typing_extra.is_annotated(f_def):
|
| 1643 |
+
(f_annotation, f_value, *_) = typing_extensions.get_args(
|
| 1644 |
+
f_def
|
| 1645 |
+
) # first two input are expected from Annotated, refer to https://docs.python.org/3/library/typing.html#typing.Annotated
|
| 1646 |
+
FieldInfo = _import_utils.import_cached_field_info()
|
| 1647 |
+
|
| 1648 |
+
if not isinstance(f_value, FieldInfo):
|
| 1649 |
+
raise PydanticUserError(
|
| 1650 |
+
'Field definitions should be a Annotated[<type>, <FieldInfo>]',
|
| 1651 |
+
code='create-model-field-definitions',
|
| 1652 |
+
)
|
| 1653 |
+
|
| 1654 |
+
else:
|
| 1655 |
+
f_annotation, f_value = None, f_def
|
| 1656 |
+
|
| 1657 |
+
if f_annotation:
|
| 1658 |
+
annotations[f_name] = f_annotation
|
| 1659 |
+
fields[f_name] = f_value
|
| 1660 |
+
|
| 1661 |
+
if __module__ is None:
|
| 1662 |
+
f = sys._getframe(1)
|
| 1663 |
+
__module__ = f.f_globals['__name__']
|
| 1664 |
+
|
| 1665 |
+
namespace: dict[str, Any] = {'__annotations__': annotations, '__module__': __module__}
|
| 1666 |
+
if __doc__:
|
| 1667 |
+
namespace.update({'__doc__': __doc__})
|
| 1668 |
+
if __validators__:
|
| 1669 |
+
namespace.update(__validators__)
|
| 1670 |
+
namespace.update(fields)
|
| 1671 |
+
if __config__:
|
| 1672 |
+
namespace['model_config'] = _config.ConfigWrapper(__config__).config_dict
|
| 1673 |
+
resolved_bases = types.resolve_bases(__base__)
|
| 1674 |
+
meta, ns, kwds = types.prepare_class(model_name, resolved_bases, kwds=__cls_kwargs__)
|
| 1675 |
+
if resolved_bases is not __base__:
|
| 1676 |
+
ns['__orig_bases__'] = __base__
|
| 1677 |
+
namespace.update(ns)
|
| 1678 |
+
|
| 1679 |
+
return meta(
|
| 1680 |
+
model_name,
|
| 1681 |
+
resolved_bases,
|
| 1682 |
+
namespace,
|
| 1683 |
+
__pydantic_reset_parent_namespace__=False,
|
| 1684 |
+
_create_model_module=__module__,
|
| 1685 |
+
**kwds,
|
| 1686 |
+
)
|
| 1687 |
+
|
| 1688 |
+
|
| 1689 |
+
__getattr__ = getattr_migration(__name__)
|
vllm/lib/python3.10/site-packages/pydantic/networks.py
ADDED
|
@@ -0,0 +1,1243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The networks module contains types for common network-related fields."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations as _annotations
|
| 4 |
+
|
| 5 |
+
import dataclasses as _dataclasses
|
| 6 |
+
import re
|
| 7 |
+
from dataclasses import fields
|
| 8 |
+
from functools import lru_cache
|
| 9 |
+
from importlib.metadata import version
|
| 10 |
+
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
|
| 11 |
+
from typing import TYPE_CHECKING, Any, ClassVar
|
| 12 |
+
|
| 13 |
+
from pydantic_core import MultiHostHost, PydanticCustomError, SchemaSerializer, core_schema
|
| 14 |
+
from pydantic_core import MultiHostUrl as _CoreMultiHostUrl
|
| 15 |
+
from pydantic_core import Url as _CoreUrl
|
| 16 |
+
from typing_extensions import Annotated, Self, TypeAlias
|
| 17 |
+
|
| 18 |
+
from pydantic.errors import PydanticUserError
|
| 19 |
+
|
| 20 |
+
from ._internal import _repr, _schema_generation_shared
|
| 21 |
+
from ._migration import getattr_migration
|
| 22 |
+
from .annotated_handlers import GetCoreSchemaHandler
|
| 23 |
+
from .json_schema import JsonSchemaValue
|
| 24 |
+
from .type_adapter import TypeAdapter
|
| 25 |
+
|
| 26 |
+
if TYPE_CHECKING:
|
| 27 |
+
import email_validator
|
| 28 |
+
|
| 29 |
+
NetworkType: TypeAlias = 'str | bytes | int | tuple[str | bytes | int, str | int]'
|
| 30 |
+
|
| 31 |
+
else:
|
| 32 |
+
email_validator = None
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
__all__ = [
|
| 36 |
+
'AnyUrl',
|
| 37 |
+
'AnyHttpUrl',
|
| 38 |
+
'FileUrl',
|
| 39 |
+
'FtpUrl',
|
| 40 |
+
'HttpUrl',
|
| 41 |
+
'WebsocketUrl',
|
| 42 |
+
'AnyWebsocketUrl',
|
| 43 |
+
'UrlConstraints',
|
| 44 |
+
'EmailStr',
|
| 45 |
+
'NameEmail',
|
| 46 |
+
'IPvAnyAddress',
|
| 47 |
+
'IPvAnyInterface',
|
| 48 |
+
'IPvAnyNetwork',
|
| 49 |
+
'PostgresDsn',
|
| 50 |
+
'CockroachDsn',
|
| 51 |
+
'AmqpDsn',
|
| 52 |
+
'RedisDsn',
|
| 53 |
+
'MongoDsn',
|
| 54 |
+
'KafkaDsn',
|
| 55 |
+
'NatsDsn',
|
| 56 |
+
'validate_email',
|
| 57 |
+
'MySQLDsn',
|
| 58 |
+
'MariaDBDsn',
|
| 59 |
+
'ClickHouseDsn',
|
| 60 |
+
'SnowflakeDsn',
|
| 61 |
+
]
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@_dataclasses.dataclass
|
| 65 |
+
class UrlConstraints:
|
| 66 |
+
"""Url constraints.
|
| 67 |
+
|
| 68 |
+
Attributes:
|
| 69 |
+
max_length: The maximum length of the url. Defaults to `None`.
|
| 70 |
+
allowed_schemes: The allowed schemes. Defaults to `None`.
|
| 71 |
+
host_required: Whether the host is required. Defaults to `None`.
|
| 72 |
+
default_host: The default host. Defaults to `None`.
|
| 73 |
+
default_port: The default port. Defaults to `None`.
|
| 74 |
+
default_path: The default path. Defaults to `None`.
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
max_length: int | None = None
|
| 78 |
+
allowed_schemes: list[str] | None = None
|
| 79 |
+
host_required: bool | None = None
|
| 80 |
+
default_host: str | None = None
|
| 81 |
+
default_port: int | None = None
|
| 82 |
+
default_path: str | None = None
|
| 83 |
+
|
| 84 |
+
def __hash__(self) -> int:
|
| 85 |
+
return hash(
|
| 86 |
+
(
|
| 87 |
+
self.max_length,
|
| 88 |
+
tuple(self.allowed_schemes) if self.allowed_schemes is not None else None,
|
| 89 |
+
self.host_required,
|
| 90 |
+
self.default_host,
|
| 91 |
+
self.default_port,
|
| 92 |
+
self.default_path,
|
| 93 |
+
)
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
@property
|
| 97 |
+
def defined_constraints(self) -> dict[str, Any]:
|
| 98 |
+
"""Fetch a key / value mapping of constraints to values that are not None. Used for core schema updates."""
|
| 99 |
+
return {field.name: value for field in fields(self) if (value := getattr(self, field.name)) is not None}
|
| 100 |
+
|
| 101 |
+
def __get_pydantic_core_schema__(self, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
|
| 102 |
+
schema = handler(source)
|
| 103 |
+
|
| 104 |
+
# for function-wrap schemas, url constraints is applied to the inner schema
|
| 105 |
+
# because when we generate schemas for urls, we wrap a core_schema.url_schema() with a function-wrap schema
|
| 106 |
+
# that helps with validation on initialization, see _BaseUrl and _BaseMultiHostUrl below.
|
| 107 |
+
schema_to_mutate = schema['schema'] if schema['type'] == 'function-wrap' else schema
|
| 108 |
+
if annotated_type := schema_to_mutate['type'] not in ('url', 'multi-host-url'):
|
| 109 |
+
raise PydanticUserError(
|
| 110 |
+
f"'UrlConstraints' cannot annotate '{annotated_type}'.", code='invalid-annotated-type'
|
| 111 |
+
)
|
| 112 |
+
for constraint_key, constraint_value in self.defined_constraints.items():
|
| 113 |
+
schema_to_mutate[constraint_key] = constraint_value
|
| 114 |
+
return schema
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class _BaseUrl:
|
| 118 |
+
_constraints: ClassVar[UrlConstraints] = UrlConstraints()
|
| 119 |
+
_url: _CoreUrl
|
| 120 |
+
|
| 121 |
+
def __init__(self, url: str | _CoreUrl | _BaseUrl) -> None:
|
| 122 |
+
self._url = _build_type_adapter(self.__class__).validate_python(url)._url
|
| 123 |
+
|
| 124 |
+
@property
|
| 125 |
+
def scheme(self) -> str:
|
| 126 |
+
"""The scheme part of the URL.
|
| 127 |
+
|
| 128 |
+
e.g. `https` in `https://user:pass@host:port/path?query#fragment`
|
| 129 |
+
"""
|
| 130 |
+
return self._url.scheme
|
| 131 |
+
|
| 132 |
+
@property
|
| 133 |
+
def username(self) -> str | None:
|
| 134 |
+
"""The username part of the URL, or `None`.
|
| 135 |
+
|
| 136 |
+
e.g. `user` in `https://user:pass@host:port/path?query#fragment`
|
| 137 |
+
"""
|
| 138 |
+
return self._url.username
|
| 139 |
+
|
| 140 |
+
@property
|
| 141 |
+
def password(self) -> str | None:
|
| 142 |
+
"""The password part of the URL, or `None`.
|
| 143 |
+
|
| 144 |
+
e.g. `pass` in `https://user:pass@host:port/path?query#fragment`
|
| 145 |
+
"""
|
| 146 |
+
return self._url.password
|
| 147 |
+
|
| 148 |
+
@property
|
| 149 |
+
def host(self) -> str | None:
|
| 150 |
+
"""The host part of the URL, or `None`.
|
| 151 |
+
|
| 152 |
+
If the URL must be punycode encoded, this is the encoded host, e.g if the input URL is `https://£££.com`,
|
| 153 |
+
`host` will be `xn--9aaa.com`
|
| 154 |
+
"""
|
| 155 |
+
return self._url.host
|
| 156 |
+
|
| 157 |
+
def unicode_host(self) -> str | None:
|
| 158 |
+
"""The host part of the URL as a unicode string, or `None`.
|
| 159 |
+
|
| 160 |
+
e.g. `host` in `https://user:pass@host:port/path?query#fragment`
|
| 161 |
+
|
| 162 |
+
If the URL must be punycode encoded, this is the decoded host, e.g if the input URL is `https://£££.com`,
|
| 163 |
+
`unicode_host()` will be `£££.com`
|
| 164 |
+
"""
|
| 165 |
+
return self._url.unicode_host()
|
| 166 |
+
|
| 167 |
+
@property
|
| 168 |
+
def port(self) -> int | None:
|
| 169 |
+
"""The port part of the URL, or `None`.
|
| 170 |
+
|
| 171 |
+
e.g. `port` in `https://user:pass@host:port/path?query#fragment`
|
| 172 |
+
"""
|
| 173 |
+
return self._url.port
|
| 174 |
+
|
| 175 |
+
@property
|
| 176 |
+
def path(self) -> str | None:
|
| 177 |
+
"""The path part of the URL, or `None`.
|
| 178 |
+
|
| 179 |
+
e.g. `/path` in `https://user:pass@host:port/path?query#fragment`
|
| 180 |
+
"""
|
| 181 |
+
return self._url.path
|
| 182 |
+
|
| 183 |
+
@property
|
| 184 |
+
def query(self) -> str | None:
|
| 185 |
+
"""The query part of the URL, or `None`.
|
| 186 |
+
|
| 187 |
+
e.g. `query` in `https://user:pass@host:port/path?query#fragment`
|
| 188 |
+
"""
|
| 189 |
+
return self._url.query
|
| 190 |
+
|
| 191 |
+
def query_params(self) -> list[tuple[str, str]]:
|
| 192 |
+
"""The query part of the URL as a list of key-value pairs.
|
| 193 |
+
|
| 194 |
+
e.g. `[('foo', 'bar')]` in `https://user:pass@host:port/path?foo=bar#fragment`
|
| 195 |
+
"""
|
| 196 |
+
return self._url.query_params()
|
| 197 |
+
|
| 198 |
+
@property
|
| 199 |
+
def fragment(self) -> str | None:
|
| 200 |
+
"""The fragment part of the URL, or `None`.
|
| 201 |
+
|
| 202 |
+
e.g. `fragment` in `https://user:pass@host:port/path?query#fragment`
|
| 203 |
+
"""
|
| 204 |
+
return self._url.fragment
|
| 205 |
+
|
| 206 |
+
def unicode_string(self) -> str:
|
| 207 |
+
"""The URL as a unicode string, unlike `__str__()` this will not punycode encode the host.
|
| 208 |
+
|
| 209 |
+
If the URL must be punycode encoded, this is the decoded string, e.g if the input URL is `https://£££.com`,
|
| 210 |
+
`unicode_string()` will be `https://£££.com`
|
| 211 |
+
"""
|
| 212 |
+
return self._url.unicode_string()
|
| 213 |
+
|
| 214 |
+
def __str__(self) -> str:
|
| 215 |
+
"""The URL as a string, this will punycode encode the host if required."""
|
| 216 |
+
return str(self._url)
|
| 217 |
+
|
| 218 |
+
def __repr__(self) -> str:
|
| 219 |
+
return f'{self.__class__.__name__}({str(self._url)!r})'
|
| 220 |
+
|
| 221 |
+
def __deepcopy__(self, memo: dict) -> Self:
|
| 222 |
+
return self.__class__(self._url)
|
| 223 |
+
|
| 224 |
+
def __eq__(self, other: Any) -> bool:
|
| 225 |
+
return self.__class__ is other.__class__ and self._url == other._url
|
| 226 |
+
|
| 227 |
+
def __hash__(self) -> int:
|
| 228 |
+
return hash(self._url)
|
| 229 |
+
|
| 230 |
+
@classmethod
|
| 231 |
+
def build(
|
| 232 |
+
cls,
|
| 233 |
+
*,
|
| 234 |
+
scheme: str,
|
| 235 |
+
username: str | None = None,
|
| 236 |
+
password: str | None = None,
|
| 237 |
+
host: str,
|
| 238 |
+
port: int | None = None,
|
| 239 |
+
path: str | None = None,
|
| 240 |
+
query: str | None = None,
|
| 241 |
+
fragment: str | None = None,
|
| 242 |
+
) -> Self:
|
| 243 |
+
"""Build a new `Url` instance from its component parts.
|
| 244 |
+
|
| 245 |
+
Args:
|
| 246 |
+
scheme: The scheme part of the URL.
|
| 247 |
+
username: The username part of the URL, or omit for no username.
|
| 248 |
+
password: The password part of the URL, or omit for no password.
|
| 249 |
+
host: The host part of the URL.
|
| 250 |
+
port: The port part of the URL, or omit for no port.
|
| 251 |
+
path: The path part of the URL, or omit for no path.
|
| 252 |
+
query: The query part of the URL, or omit for no query.
|
| 253 |
+
fragment: The fragment part of the URL, or omit for no fragment.
|
| 254 |
+
|
| 255 |
+
Returns:
|
| 256 |
+
An instance of URL
|
| 257 |
+
"""
|
| 258 |
+
return cls(
|
| 259 |
+
_CoreUrl.build(
|
| 260 |
+
scheme=scheme,
|
| 261 |
+
username=username,
|
| 262 |
+
password=password,
|
| 263 |
+
host=host,
|
| 264 |
+
port=port,
|
| 265 |
+
path=path,
|
| 266 |
+
query=query,
|
| 267 |
+
fragment=fragment,
|
| 268 |
+
)
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
@classmethod
|
| 272 |
+
def __get_pydantic_core_schema__(
|
| 273 |
+
cls, source: type[_BaseUrl], handler: GetCoreSchemaHandler
|
| 274 |
+
) -> core_schema.CoreSchema:
|
| 275 |
+
def wrap_val(v, h):
|
| 276 |
+
if isinstance(v, source):
|
| 277 |
+
return v
|
| 278 |
+
if isinstance(v, _BaseUrl):
|
| 279 |
+
v = str(v)
|
| 280 |
+
core_url = h(v)
|
| 281 |
+
instance = source.__new__(source)
|
| 282 |
+
instance._url = core_url
|
| 283 |
+
return instance
|
| 284 |
+
|
| 285 |
+
return core_schema.no_info_wrap_validator_function(
|
| 286 |
+
wrap_val,
|
| 287 |
+
schema=core_schema.url_schema(**cls._constraints.defined_constraints),
|
| 288 |
+
serialization=core_schema.to_string_ser_schema(),
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
@classmethod
|
| 292 |
+
def __get_pydantic_json_schema__(
|
| 293 |
+
cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler
|
| 294 |
+
) -> JsonSchemaValue:
|
| 295 |
+
# we use the url schema for json schema generation, but we might have to extract it from
|
| 296 |
+
# the function-wrap schema we use as a tool for validation on initialization
|
| 297 |
+
inner_schema = core_schema['schema'] if core_schema['type'] == 'function-wrap' else core_schema
|
| 298 |
+
return handler(inner_schema)
|
| 299 |
+
|
| 300 |
+
__pydantic_serializer__ = SchemaSerializer(core_schema.any_schema(serialization=core_schema.to_string_ser_schema()))
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
class _BaseMultiHostUrl:
|
| 304 |
+
_constraints: ClassVar[UrlConstraints] = UrlConstraints()
|
| 305 |
+
_url: _CoreMultiHostUrl
|
| 306 |
+
|
| 307 |
+
def __init__(self, url: str | _CoreMultiHostUrl | _BaseMultiHostUrl) -> None:
|
| 308 |
+
self._url = _build_type_adapter(self.__class__).validate_python(url)._url
|
| 309 |
+
|
| 310 |
+
@property
|
| 311 |
+
def scheme(self) -> str:
|
| 312 |
+
"""The scheme part of the URL.
|
| 313 |
+
|
| 314 |
+
e.g. `https` in `https://foo.com,bar.com/path?query#fragment`
|
| 315 |
+
"""
|
| 316 |
+
return self._url.scheme
|
| 317 |
+
|
| 318 |
+
@property
|
| 319 |
+
def path(self) -> str | None:
|
| 320 |
+
"""The path part of the URL, or `None`.
|
| 321 |
+
|
| 322 |
+
e.g. `/path` in `https://foo.com,bar.com/path?query#fragment`
|
| 323 |
+
"""
|
| 324 |
+
return self._url.path
|
| 325 |
+
|
| 326 |
+
@property
|
| 327 |
+
def query(self) -> str | None:
|
| 328 |
+
"""The query part of the URL, or `None`.
|
| 329 |
+
|
| 330 |
+
e.g. `query` in `https://foo.com,bar.com/path?query#fragment`
|
| 331 |
+
"""
|
| 332 |
+
return self._url.query
|
| 333 |
+
|
| 334 |
+
def query_params(self) -> list[tuple[str, str]]:
|
| 335 |
+
"""The query part of the URL as a list of key-value pairs.
|
| 336 |
+
|
| 337 |
+
e.g. `[('foo', 'bar')]` in `https://foo.com,bar.com/path?query#fragment`
|
| 338 |
+
"""
|
| 339 |
+
return self._url.query_params()
|
| 340 |
+
|
| 341 |
+
@property
|
| 342 |
+
def fragment(self) -> str | None:
|
| 343 |
+
"""The fragment part of the URL, or `None`.
|
| 344 |
+
|
| 345 |
+
e.g. `fragment` in `https://foo.com,bar.com/path?query#fragment`
|
| 346 |
+
"""
|
| 347 |
+
return self._url.fragment
|
| 348 |
+
|
| 349 |
+
def hosts(self) -> list[MultiHostHost]:
|
| 350 |
+
'''The hosts of the `MultiHostUrl` as [`MultiHostHost`][pydantic_core.MultiHostHost] typed dicts.
|
| 351 |
+
|
| 352 |
+
```python
|
| 353 |
+
from pydantic_core import MultiHostUrl
|
| 354 |
+
|
| 355 |
+
mhu = MultiHostUrl('https://foo.com:123,foo:bar@bar.com/path')
|
| 356 |
+
print(mhu.hosts())
|
| 357 |
+
"""
|
| 358 |
+
[
|
| 359 |
+
{'username': None, 'password': None, 'host': 'foo.com', 'port': 123},
|
| 360 |
+
{'username': 'foo', 'password': 'bar', 'host': 'bar.com', 'port': 443}
|
| 361 |
+
]
|
| 362 |
+
```
|
| 363 |
+
Returns:
|
| 364 |
+
A list of dicts, each representing a host.
|
| 365 |
+
'''
|
| 366 |
+
return self._url.hosts()
|
| 367 |
+
|
| 368 |
+
def unicode_string(self) -> str:
|
| 369 |
+
"""The URL as a unicode string, unlike `__str__()` this will not punycode encode the hosts."""
|
| 370 |
+
return self._url.unicode_string()
|
| 371 |
+
|
| 372 |
+
def __str__(self) -> str:
|
| 373 |
+
"""The URL as a string, this will punycode encode the host if required."""
|
| 374 |
+
return str(self._url)
|
| 375 |
+
|
| 376 |
+
def __repr__(self) -> str:
|
| 377 |
+
return f'{self.__class__.__name__}({str(self._url)!r})'
|
| 378 |
+
|
| 379 |
+
def __deepcopy__(self, memo: dict) -> Self:
|
| 380 |
+
return self.__class__(self._url)
|
| 381 |
+
|
| 382 |
+
def __eq__(self, other: Any) -> bool:
|
| 383 |
+
return self.__class__ is other.__class__ and self._url == other._url
|
| 384 |
+
|
| 385 |
+
def __hash__(self) -> int:
|
| 386 |
+
return hash(self._url)
|
| 387 |
+
|
| 388 |
+
@classmethod
|
| 389 |
+
def build(
|
| 390 |
+
cls,
|
| 391 |
+
*,
|
| 392 |
+
scheme: str,
|
| 393 |
+
hosts: list[MultiHostHost] | None = None,
|
| 394 |
+
username: str | None = None,
|
| 395 |
+
password: str | None = None,
|
| 396 |
+
host: str | None = None,
|
| 397 |
+
port: int | None = None,
|
| 398 |
+
path: str | None = None,
|
| 399 |
+
query: str | None = None,
|
| 400 |
+
fragment: str | None = None,
|
| 401 |
+
) -> Self:
|
| 402 |
+
"""Build a new `MultiHostUrl` instance from its component parts.
|
| 403 |
+
|
| 404 |
+
This method takes either `hosts` - a list of `MultiHostHost` typed dicts, or the individual components
|
| 405 |
+
`username`, `password`, `host` and `port`.
|
| 406 |
+
|
| 407 |
+
Args:
|
| 408 |
+
scheme: The scheme part of the URL.
|
| 409 |
+
hosts: Multiple hosts to build the URL from.
|
| 410 |
+
username: The username part of the URL.
|
| 411 |
+
password: The password part of the URL.
|
| 412 |
+
host: The host part of the URL.
|
| 413 |
+
port: The port part of the URL.
|
| 414 |
+
path: The path part of the URL.
|
| 415 |
+
query: The query part of the URL, or omit for no query.
|
| 416 |
+
fragment: The fragment part of the URL, or omit for no fragment.
|
| 417 |
+
|
| 418 |
+
Returns:
|
| 419 |
+
An instance of `MultiHostUrl`
|
| 420 |
+
"""
|
| 421 |
+
return cls(
|
| 422 |
+
_CoreMultiHostUrl.build(
|
| 423 |
+
scheme=scheme,
|
| 424 |
+
hosts=hosts,
|
| 425 |
+
username=username,
|
| 426 |
+
password=password,
|
| 427 |
+
host=host,
|
| 428 |
+
port=port,
|
| 429 |
+
path=path,
|
| 430 |
+
query=query,
|
| 431 |
+
fragment=fragment,
|
| 432 |
+
)
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
@classmethod
|
| 436 |
+
def __get_pydantic_core_schema__(
|
| 437 |
+
cls, source: type[_BaseMultiHostUrl], handler: GetCoreSchemaHandler
|
| 438 |
+
) -> core_schema.CoreSchema:
|
| 439 |
+
def wrap_val(v, h):
|
| 440 |
+
if isinstance(v, source):
|
| 441 |
+
return v
|
| 442 |
+
if isinstance(v, _BaseMultiHostUrl):
|
| 443 |
+
v = str(v)
|
| 444 |
+
core_url = h(v)
|
| 445 |
+
instance = source.__new__(source)
|
| 446 |
+
instance._url = core_url
|
| 447 |
+
return instance
|
| 448 |
+
|
| 449 |
+
return core_schema.no_info_wrap_validator_function(
|
| 450 |
+
wrap_val,
|
| 451 |
+
schema=core_schema.multi_host_url_schema(**cls._constraints.defined_constraints),
|
| 452 |
+
serialization=core_schema.to_string_ser_schema(),
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
@classmethod
|
| 456 |
+
def __get_pydantic_json_schema__(
|
| 457 |
+
cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler
|
| 458 |
+
) -> JsonSchemaValue:
|
| 459 |
+
# we use the url schema for json schema generation, but we might have to extract it from
|
| 460 |
+
# the function-wrap schema we use as a tool for validation on initialization
|
| 461 |
+
inner_schema = core_schema['schema'] if core_schema['type'] == 'function-wrap' else core_schema
|
| 462 |
+
return handler(inner_schema)
|
| 463 |
+
|
| 464 |
+
__pydantic_serializer__ = SchemaSerializer(core_schema.any_schema(serialization=core_schema.to_string_ser_schema()))
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
@lru_cache
|
| 468 |
+
def _build_type_adapter(cls: type[_BaseUrl | _BaseMultiHostUrl]) -> TypeAdapter:
|
| 469 |
+
return TypeAdapter(cls)
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
class AnyUrl(_BaseUrl):
|
| 473 |
+
"""Base type for all URLs.
|
| 474 |
+
|
| 475 |
+
* Any scheme allowed
|
| 476 |
+
* Top-level domain (TLD) not required
|
| 477 |
+
* Host not required
|
| 478 |
+
|
| 479 |
+
Assuming an input URL of `http://samuel:pass@example.com:8000/the/path/?query=here#fragment=is;this=bit`,
|
| 480 |
+
the types export the following properties:
|
| 481 |
+
|
| 482 |
+
- `scheme`: the URL scheme (`http`), always set.
|
| 483 |
+
- `host`: the URL host (`example.com`).
|
| 484 |
+
- `username`: optional username if included (`samuel`).
|
| 485 |
+
- `password`: optional password if included (`pass`).
|
| 486 |
+
- `port`: optional port (`8000`).
|
| 487 |
+
- `path`: optional path (`/the/path/`).
|
| 488 |
+
- `query`: optional URL query (for example, `GET` arguments or "search string", such as `query=here`).
|
| 489 |
+
- `fragment`: optional fragment (`fragment=is;this=bit`).
|
| 490 |
+
"""
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
# Note: all single host urls inherit from `AnyUrl` to preserve compatibility with pre-v2.10 code
|
| 494 |
+
# Where urls were annotated variants of `AnyUrl`, which was an alias to `pydantic_core.Url`
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
class AnyHttpUrl(AnyUrl):
|
| 498 |
+
"""A type that will accept any http or https URL.
|
| 499 |
+
|
| 500 |
+
* TLD not required
|
| 501 |
+
* Host not required
|
| 502 |
+
"""
|
| 503 |
+
|
| 504 |
+
_constraints = UrlConstraints(allowed_schemes=['http', 'https'])
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
class HttpUrl(AnyUrl):
|
| 508 |
+
"""A type that will accept any http or https URL.
|
| 509 |
+
|
| 510 |
+
* TLD not required
|
| 511 |
+
* Host not required
|
| 512 |
+
* Max length 2083
|
| 513 |
+
|
| 514 |
+
```python
|
| 515 |
+
from pydantic import BaseModel, HttpUrl, ValidationError
|
| 516 |
+
|
| 517 |
+
class MyModel(BaseModel):
|
| 518 |
+
url: HttpUrl
|
| 519 |
+
|
| 520 |
+
m = MyModel(url='http://www.example.com') # (1)!
|
| 521 |
+
print(m.url)
|
| 522 |
+
#> http://www.example.com/
|
| 523 |
+
|
| 524 |
+
try:
|
| 525 |
+
MyModel(url='ftp://invalid.url')
|
| 526 |
+
except ValidationError as e:
|
| 527 |
+
print(e)
|
| 528 |
+
'''
|
| 529 |
+
1 validation error for MyModel
|
| 530 |
+
url
|
| 531 |
+
URL scheme should be 'http' or 'https' [type=url_scheme, input_value='ftp://invalid.url', input_type=str]
|
| 532 |
+
'''
|
| 533 |
+
|
| 534 |
+
try:
|
| 535 |
+
MyModel(url='not a url')
|
| 536 |
+
except ValidationError as e:
|
| 537 |
+
print(e)
|
| 538 |
+
'''
|
| 539 |
+
1 validation error for MyModel
|
| 540 |
+
url
|
| 541 |
+
Input should be a valid URL, relative URL without a base [type=url_parsing, input_value='not a url', input_type=str]
|
| 542 |
+
'''
|
| 543 |
+
```
|
| 544 |
+
|
| 545 |
+
1. Note: mypy would prefer `m = MyModel(url=HttpUrl('http://www.example.com'))`, but Pydantic will convert the string to an HttpUrl instance anyway.
|
| 546 |
+
|
| 547 |
+
"International domains" (e.g. a URL where the host or TLD includes non-ascii characters) will be encoded via
|
| 548 |
+
[punycode](https://en.wikipedia.org/wiki/Punycode) (see
|
| 549 |
+
[this article](https://www.xudongz.com/blog/2017/idn-phishing/) for a good description of why this is important):
|
| 550 |
+
|
| 551 |
+
```python
|
| 552 |
+
from pydantic import BaseModel, HttpUrl
|
| 553 |
+
|
| 554 |
+
class MyModel(BaseModel):
|
| 555 |
+
url: HttpUrl
|
| 556 |
+
|
| 557 |
+
m1 = MyModel(url='http://puny£code.com')
|
| 558 |
+
print(m1.url)
|
| 559 |
+
#> http://xn--punycode-eja.com/
|
| 560 |
+
m2 = MyModel(url='https://www.аррӏе.com/')
|
| 561 |
+
print(m2.url)
|
| 562 |
+
#> https://www.xn--80ak6aa92e.com/
|
| 563 |
+
m3 = MyModel(url='https://www.example.珠宝/')
|
| 564 |
+
print(m3.url)
|
| 565 |
+
#> https://www.example.xn--pbt977c/
|
| 566 |
+
```
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
!!! warning "Underscores in Hostnames"
|
| 570 |
+
In Pydantic, underscores are allowed in all parts of a domain except the TLD.
|
| 571 |
+
Technically this might be wrong - in theory the hostname cannot have underscores, but subdomains can.
|
| 572 |
+
|
| 573 |
+
To explain this; consider the following two cases:
|
| 574 |
+
|
| 575 |
+
- `exam_ple.co.uk`: the hostname is `exam_ple`, which should not be allowed since it contains an underscore.
|
| 576 |
+
- `foo_bar.example.com` the hostname is `example`, which should be allowed since the underscore is in the subdomain.
|
| 577 |
+
|
| 578 |
+
Without having an exhaustive list of TLDs, it would be impossible to differentiate between these two. Therefore
|
| 579 |
+
underscores are allowed, but you can always do further validation in a validator if desired.
|
| 580 |
+
|
| 581 |
+
Also, Chrome, Firefox, and Safari all currently accept `http://exam_ple.com` as a URL, so we're in good
|
| 582 |
+
(or at least big) company.
|
| 583 |
+
"""
|
| 584 |
+
|
| 585 |
+
_constraints = UrlConstraints(max_length=2083, allowed_schemes=['http', 'https'])
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
class AnyWebsocketUrl(AnyUrl):
|
| 589 |
+
"""A type that will accept any ws or wss URL.
|
| 590 |
+
|
| 591 |
+
* TLD not required
|
| 592 |
+
* Host not required
|
| 593 |
+
"""
|
| 594 |
+
|
| 595 |
+
_constraints = UrlConstraints(allowed_schemes=['ws', 'wss'])
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
class WebsocketUrl(AnyUrl):
|
| 599 |
+
"""A type that will accept any ws or wss URL.
|
| 600 |
+
|
| 601 |
+
* TLD not required
|
| 602 |
+
* Host not required
|
| 603 |
+
* Max length 2083
|
| 604 |
+
"""
|
| 605 |
+
|
| 606 |
+
_constraints = UrlConstraints(max_length=2083, allowed_schemes=['ws', 'wss'])
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
class FileUrl(AnyUrl):
|
| 610 |
+
"""A type that will accept any file URL.
|
| 611 |
+
|
| 612 |
+
* Host not required
|
| 613 |
+
"""
|
| 614 |
+
|
| 615 |
+
_constraints = UrlConstraints(allowed_schemes=['file'])
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
class FtpUrl(AnyUrl):
|
| 619 |
+
"""A type that will accept ftp URL.
|
| 620 |
+
|
| 621 |
+
* TLD not required
|
| 622 |
+
* Host not required
|
| 623 |
+
"""
|
| 624 |
+
|
| 625 |
+
_constraints = UrlConstraints(allowed_schemes=['ftp'])
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
class PostgresDsn(_BaseMultiHostUrl):
|
| 629 |
+
"""A type that will accept any Postgres DSN.
|
| 630 |
+
|
| 631 |
+
* User info required
|
| 632 |
+
* TLD not required
|
| 633 |
+
* Host required
|
| 634 |
+
* Supports multiple hosts
|
| 635 |
+
|
| 636 |
+
If further validation is required, these properties can be used by validators to enforce specific behaviour:
|
| 637 |
+
|
| 638 |
+
```python
|
| 639 |
+
from pydantic import (
|
| 640 |
+
BaseModel,
|
| 641 |
+
HttpUrl,
|
| 642 |
+
PostgresDsn,
|
| 643 |
+
ValidationError,
|
| 644 |
+
field_validator,
|
| 645 |
+
)
|
| 646 |
+
|
| 647 |
+
class MyModel(BaseModel):
|
| 648 |
+
url: HttpUrl
|
| 649 |
+
|
| 650 |
+
m = MyModel(url='http://www.example.com')
|
| 651 |
+
|
| 652 |
+
# the repr() method for a url will display all properties of the url
|
| 653 |
+
print(repr(m.url))
|
| 654 |
+
#> HttpUrl('http://www.example.com/')
|
| 655 |
+
print(m.url.scheme)
|
| 656 |
+
#> http
|
| 657 |
+
print(m.url.host)
|
| 658 |
+
#> www.example.com
|
| 659 |
+
print(m.url.port)
|
| 660 |
+
#> 80
|
| 661 |
+
|
| 662 |
+
class MyDatabaseModel(BaseModel):
|
| 663 |
+
db: PostgresDsn
|
| 664 |
+
|
| 665 |
+
@field_validator('db')
|
| 666 |
+
def check_db_name(cls, v):
|
| 667 |
+
assert v.path and len(v.path) > 1, 'database must be provided'
|
| 668 |
+
return v
|
| 669 |
+
|
| 670 |
+
m = MyDatabaseModel(db='postgres://user:pass@localhost:5432/foobar')
|
| 671 |
+
print(m.db)
|
| 672 |
+
#> postgres://user:pass@localhost:5432/foobar
|
| 673 |
+
|
| 674 |
+
try:
|
| 675 |
+
MyDatabaseModel(db='postgres://user:pass@localhost:5432')
|
| 676 |
+
except ValidationError as e:
|
| 677 |
+
print(e)
|
| 678 |
+
'''
|
| 679 |
+
1 validation error for MyDatabaseModel
|
| 680 |
+
db
|
| 681 |
+
Assertion failed, database must be provided
|
| 682 |
+
assert (None)
|
| 683 |
+
+ where None = PostgresDsn('postgres://user:pass@localhost:5432').path [type=assertion_error, input_value='postgres://user:pass@localhost:5432', input_type=str]
|
| 684 |
+
'''
|
| 685 |
+
```
|
| 686 |
+
"""
|
| 687 |
+
|
| 688 |
+
_constraints = UrlConstraints(
|
| 689 |
+
host_required=True,
|
| 690 |
+
allowed_schemes=[
|
| 691 |
+
'postgres',
|
| 692 |
+
'postgresql',
|
| 693 |
+
'postgresql+asyncpg',
|
| 694 |
+
'postgresql+pg8000',
|
| 695 |
+
'postgresql+psycopg',
|
| 696 |
+
'postgresql+psycopg2',
|
| 697 |
+
'postgresql+psycopg2cffi',
|
| 698 |
+
'postgresql+py-postgresql',
|
| 699 |
+
'postgresql+pygresql',
|
| 700 |
+
],
|
| 701 |
+
)
|
| 702 |
+
|
| 703 |
+
@property
|
| 704 |
+
def host(self) -> str:
|
| 705 |
+
"""The required URL host."""
|
| 706 |
+
return self._url.host # pyright: ignore[reportAttributeAccessIssue]
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
class CockroachDsn(AnyUrl):
|
| 710 |
+
"""A type that will accept any Cockroach DSN.
|
| 711 |
+
|
| 712 |
+
* User info required
|
| 713 |
+
* TLD not required
|
| 714 |
+
* Host required
|
| 715 |
+
"""
|
| 716 |
+
|
| 717 |
+
_constraints = UrlConstraints(
|
| 718 |
+
host_required=True,
|
| 719 |
+
allowed_schemes=[
|
| 720 |
+
'cockroachdb',
|
| 721 |
+
'cockroachdb+psycopg2',
|
| 722 |
+
'cockroachdb+asyncpg',
|
| 723 |
+
],
|
| 724 |
+
)
|
| 725 |
+
|
| 726 |
+
@property
|
| 727 |
+
def host(self) -> str:
|
| 728 |
+
"""The required URL host."""
|
| 729 |
+
return self._url.host # pyright: ignore[reportReturnType]
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
class AmqpDsn(AnyUrl):
|
| 733 |
+
"""A type that will accept any AMQP DSN.
|
| 734 |
+
|
| 735 |
+
* User info required
|
| 736 |
+
* TLD not required
|
| 737 |
+
* Host not required
|
| 738 |
+
"""
|
| 739 |
+
|
| 740 |
+
_constraints = UrlConstraints(allowed_schemes=['amqp', 'amqps'])
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
class RedisDsn(AnyUrl):
|
| 744 |
+
"""A type that will accept any Redis DSN.
|
| 745 |
+
|
| 746 |
+
* User info required
|
| 747 |
+
* TLD not required
|
| 748 |
+
* Host required (e.g., `rediss://:pass@localhost`)
|
| 749 |
+
"""
|
| 750 |
+
|
| 751 |
+
_constraints = UrlConstraints(
|
| 752 |
+
allowed_schemes=['redis', 'rediss'],
|
| 753 |
+
default_host='localhost',
|
| 754 |
+
default_port=6379,
|
| 755 |
+
default_path='/0',
|
| 756 |
+
host_required=True,
|
| 757 |
+
)
|
| 758 |
+
|
| 759 |
+
@property
|
| 760 |
+
def host(self) -> str:
|
| 761 |
+
"""The required URL host."""
|
| 762 |
+
return self._url.host # pyright: ignore[reportReturnType]
|
| 763 |
+
|
| 764 |
+
|
| 765 |
+
class MongoDsn(_BaseMultiHostUrl):
|
| 766 |
+
"""A type that will accept any MongoDB DSN.
|
| 767 |
+
|
| 768 |
+
* User info not required
|
| 769 |
+
* Database name not required
|
| 770 |
+
* Port not required
|
| 771 |
+
* User info may be passed without user part (e.g., `mongodb://mongodb0.example.com:27017`).
|
| 772 |
+
"""
|
| 773 |
+
|
| 774 |
+
_constraints = UrlConstraints(allowed_schemes=['mongodb', 'mongodb+srv'], default_port=27017)
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
class KafkaDsn(AnyUrl):
|
| 778 |
+
"""A type that will accept any Kafka DSN.
|
| 779 |
+
|
| 780 |
+
* User info required
|
| 781 |
+
* TLD not required
|
| 782 |
+
* Host not required
|
| 783 |
+
"""
|
| 784 |
+
|
| 785 |
+
_constraints = UrlConstraints(allowed_schemes=['kafka'], default_host='localhost', default_port=9092)
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
class NatsDsn(_BaseMultiHostUrl):
|
| 789 |
+
"""A type that will accept any NATS DSN.
|
| 790 |
+
|
| 791 |
+
NATS is a connective technology built for the ever increasingly hyper-connected world.
|
| 792 |
+
It is a single technology that enables applications to securely communicate across
|
| 793 |
+
any combination of cloud vendors, on-premise, edge, web and mobile, and devices.
|
| 794 |
+
More: https://nats.io
|
| 795 |
+
"""
|
| 796 |
+
|
| 797 |
+
_constraints = UrlConstraints(
|
| 798 |
+
allowed_schemes=['nats', 'tls', 'ws', 'wss'], default_host='localhost', default_port=4222
|
| 799 |
+
)
|
| 800 |
+
|
| 801 |
+
|
| 802 |
+
class MySQLDsn(AnyUrl):
|
| 803 |
+
"""A type that will accept any MySQL DSN.
|
| 804 |
+
|
| 805 |
+
* User info required
|
| 806 |
+
* TLD not required
|
| 807 |
+
* Host not required
|
| 808 |
+
"""
|
| 809 |
+
|
| 810 |
+
_constraints = UrlConstraints(
|
| 811 |
+
allowed_schemes=[
|
| 812 |
+
'mysql',
|
| 813 |
+
'mysql+mysqlconnector',
|
| 814 |
+
'mysql+aiomysql',
|
| 815 |
+
'mysql+asyncmy',
|
| 816 |
+
'mysql+mysqldb',
|
| 817 |
+
'mysql+pymysql',
|
| 818 |
+
'mysql+cymysql',
|
| 819 |
+
'mysql+pyodbc',
|
| 820 |
+
],
|
| 821 |
+
default_port=3306,
|
| 822 |
+
host_required=True,
|
| 823 |
+
)
|
| 824 |
+
|
| 825 |
+
|
| 826 |
+
class MariaDBDsn(AnyUrl):
|
| 827 |
+
"""A type that will accept any MariaDB DSN.
|
| 828 |
+
|
| 829 |
+
* User info required
|
| 830 |
+
* TLD not required
|
| 831 |
+
* Host not required
|
| 832 |
+
"""
|
| 833 |
+
|
| 834 |
+
_constraints = UrlConstraints(
|
| 835 |
+
allowed_schemes=['mariadb', 'mariadb+mariadbconnector', 'mariadb+pymysql'],
|
| 836 |
+
default_port=3306,
|
| 837 |
+
)
|
| 838 |
+
|
| 839 |
+
|
| 840 |
+
class ClickHouseDsn(AnyUrl):
|
| 841 |
+
"""A type that will accept any ClickHouse DSN.
|
| 842 |
+
|
| 843 |
+
* User info required
|
| 844 |
+
* TLD not required
|
| 845 |
+
* Host not required
|
| 846 |
+
"""
|
| 847 |
+
|
| 848 |
+
_constraints = UrlConstraints(
|
| 849 |
+
allowed_schemes=['clickhouse+native', 'clickhouse+asynch'],
|
| 850 |
+
default_host='localhost',
|
| 851 |
+
default_port=9000,
|
| 852 |
+
)
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
class SnowflakeDsn(AnyUrl):
|
| 856 |
+
"""A type that will accept any Snowflake DSN.
|
| 857 |
+
|
| 858 |
+
* User info required
|
| 859 |
+
* TLD not required
|
| 860 |
+
* Host required
|
| 861 |
+
"""
|
| 862 |
+
|
| 863 |
+
_constraints = UrlConstraints(
|
| 864 |
+
allowed_schemes=['snowflake'],
|
| 865 |
+
host_required=True,
|
| 866 |
+
)
|
| 867 |
+
|
| 868 |
+
@property
|
| 869 |
+
def host(self) -> str:
|
| 870 |
+
"""The required URL host."""
|
| 871 |
+
return self._url.host # pyright: ignore[reportReturnType]
|
| 872 |
+
|
| 873 |
+
|
| 874 |
+
def import_email_validator() -> None:
|
| 875 |
+
global email_validator
|
| 876 |
+
try:
|
| 877 |
+
import email_validator
|
| 878 |
+
except ImportError as e:
|
| 879 |
+
raise ImportError('email-validator is not installed, run `pip install pydantic[email]`') from e
|
| 880 |
+
if not version('email-validator').partition('.')[0] == '2':
|
| 881 |
+
raise ImportError('email-validator version >= 2.0 required, run pip install -U email-validator')
|
| 882 |
+
|
| 883 |
+
|
| 884 |
+
if TYPE_CHECKING:
|
| 885 |
+
EmailStr = Annotated[str, ...]
|
| 886 |
+
else:
|
| 887 |
+
|
| 888 |
+
class EmailStr:
|
| 889 |
+
"""
|
| 890 |
+
Info:
|
| 891 |
+
To use this type, you need to install the optional
|
| 892 |
+
[`email-validator`](https://github.com/JoshData/python-email-validator) package:
|
| 893 |
+
|
| 894 |
+
```bash
|
| 895 |
+
pip install email-validator
|
| 896 |
+
```
|
| 897 |
+
|
| 898 |
+
Validate email addresses.
|
| 899 |
+
|
| 900 |
+
```python
|
| 901 |
+
from pydantic import BaseModel, EmailStr
|
| 902 |
+
|
| 903 |
+
class Model(BaseModel):
|
| 904 |
+
email: EmailStr
|
| 905 |
+
|
| 906 |
+
print(Model(email='contact@mail.com'))
|
| 907 |
+
#> email='contact@mail.com'
|
| 908 |
+
```
|
| 909 |
+
""" # noqa: D212
|
| 910 |
+
|
| 911 |
+
@classmethod
|
| 912 |
+
def __get_pydantic_core_schema__(
|
| 913 |
+
cls,
|
| 914 |
+
_source: type[Any],
|
| 915 |
+
_handler: GetCoreSchemaHandler,
|
| 916 |
+
) -> core_schema.CoreSchema:
|
| 917 |
+
import_email_validator()
|
| 918 |
+
return core_schema.no_info_after_validator_function(cls._validate, core_schema.str_schema())
|
| 919 |
+
|
| 920 |
+
@classmethod
|
| 921 |
+
def __get_pydantic_json_schema__(
|
| 922 |
+
cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler
|
| 923 |
+
) -> JsonSchemaValue:
|
| 924 |
+
field_schema = handler(core_schema)
|
| 925 |
+
field_schema.update(type='string', format='email')
|
| 926 |
+
return field_schema
|
| 927 |
+
|
| 928 |
+
@classmethod
|
| 929 |
+
def _validate(cls, input_value: str, /) -> str:
|
| 930 |
+
return validate_email(input_value)[1]
|
| 931 |
+
|
| 932 |
+
|
| 933 |
+
class NameEmail(_repr.Representation):
|
| 934 |
+
"""
|
| 935 |
+
Info:
|
| 936 |
+
To use this type, you need to install the optional
|
| 937 |
+
[`email-validator`](https://github.com/JoshData/python-email-validator) package:
|
| 938 |
+
|
| 939 |
+
```bash
|
| 940 |
+
pip install email-validator
|
| 941 |
+
```
|
| 942 |
+
|
| 943 |
+
Validate a name and email address combination, as specified by
|
| 944 |
+
[RFC 5322](https://datatracker.ietf.org/doc/html/rfc5322#section-3.4).
|
| 945 |
+
|
| 946 |
+
The `NameEmail` has two properties: `name` and `email`.
|
| 947 |
+
In case the `name` is not provided, it's inferred from the email address.
|
| 948 |
+
|
| 949 |
+
```python
|
| 950 |
+
from pydantic import BaseModel, NameEmail
|
| 951 |
+
|
| 952 |
+
class User(BaseModel):
|
| 953 |
+
email: NameEmail
|
| 954 |
+
|
| 955 |
+
user = User(email='Fred Bloggs <fred.bloggs@example.com>')
|
| 956 |
+
print(user.email)
|
| 957 |
+
#> Fred Bloggs <fred.bloggs@example.com>
|
| 958 |
+
print(user.email.name)
|
| 959 |
+
#> Fred Bloggs
|
| 960 |
+
|
| 961 |
+
user = User(email='fred.bloggs@example.com')
|
| 962 |
+
print(user.email)
|
| 963 |
+
#> fred.bloggs <fred.bloggs@example.com>
|
| 964 |
+
print(user.email.name)
|
| 965 |
+
#> fred.bloggs
|
| 966 |
+
```
|
| 967 |
+
""" # noqa: D212
|
| 968 |
+
|
| 969 |
+
__slots__ = 'name', 'email'
|
| 970 |
+
|
| 971 |
+
def __init__(self, name: str, email: str):
|
| 972 |
+
self.name = name
|
| 973 |
+
self.email = email
|
| 974 |
+
|
| 975 |
+
def __eq__(self, other: Any) -> bool:
|
| 976 |
+
return isinstance(other, NameEmail) and (self.name, self.email) == (other.name, other.email)
|
| 977 |
+
|
| 978 |
+
@classmethod
|
| 979 |
+
def __get_pydantic_json_schema__(
|
| 980 |
+
cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler
|
| 981 |
+
) -> JsonSchemaValue:
|
| 982 |
+
field_schema = handler(core_schema)
|
| 983 |
+
field_schema.update(type='string', format='name-email')
|
| 984 |
+
return field_schema
|
| 985 |
+
|
| 986 |
+
@classmethod
|
| 987 |
+
def __get_pydantic_core_schema__(
|
| 988 |
+
cls,
|
| 989 |
+
_source: type[Any],
|
| 990 |
+
_handler: GetCoreSchemaHandler,
|
| 991 |
+
) -> core_schema.CoreSchema:
|
| 992 |
+
import_email_validator()
|
| 993 |
+
|
| 994 |
+
return core_schema.no_info_after_validator_function(
|
| 995 |
+
cls._validate,
|
| 996 |
+
core_schema.json_or_python_schema(
|
| 997 |
+
json_schema=core_schema.str_schema(),
|
| 998 |
+
python_schema=core_schema.union_schema(
|
| 999 |
+
[core_schema.is_instance_schema(cls), core_schema.str_schema()],
|
| 1000 |
+
custom_error_type='name_email_type',
|
| 1001 |
+
custom_error_message='Input is not a valid NameEmail',
|
| 1002 |
+
),
|
| 1003 |
+
serialization=core_schema.to_string_ser_schema(),
|
| 1004 |
+
),
|
| 1005 |
+
)
|
| 1006 |
+
|
| 1007 |
+
@classmethod
|
| 1008 |
+
def _validate(cls, input_value: Self | str, /) -> Self:
|
| 1009 |
+
if isinstance(input_value, str):
|
| 1010 |
+
name, email = validate_email(input_value)
|
| 1011 |
+
return cls(name, email)
|
| 1012 |
+
else:
|
| 1013 |
+
return input_value
|
| 1014 |
+
|
| 1015 |
+
def __str__(self) -> str:
|
| 1016 |
+
if '@' in self.name:
|
| 1017 |
+
return f'"{self.name}" <{self.email}>'
|
| 1018 |
+
|
| 1019 |
+
return f'{self.name} <{self.email}>'
|
| 1020 |
+
|
| 1021 |
+
|
| 1022 |
+
IPvAnyAddressType: TypeAlias = 'IPv4Address | IPv6Address'
|
| 1023 |
+
IPvAnyInterfaceType: TypeAlias = 'IPv4Interface | IPv6Interface'
|
| 1024 |
+
IPvAnyNetworkType: TypeAlias = 'IPv4Network | IPv6Network'
|
| 1025 |
+
|
| 1026 |
+
if TYPE_CHECKING:
|
| 1027 |
+
IPvAnyAddress = IPvAnyAddressType
|
| 1028 |
+
IPvAnyInterface = IPvAnyInterfaceType
|
| 1029 |
+
IPvAnyNetwork = IPvAnyNetworkType
|
| 1030 |
+
else:
|
| 1031 |
+
|
| 1032 |
+
class IPvAnyAddress:
|
| 1033 |
+
"""Validate an IPv4 or IPv6 address.
|
| 1034 |
+
|
| 1035 |
+
```python
|
| 1036 |
+
from pydantic import BaseModel
|
| 1037 |
+
from pydantic.networks import IPvAnyAddress
|
| 1038 |
+
|
| 1039 |
+
class IpModel(BaseModel):
|
| 1040 |
+
ip: IPvAnyAddress
|
| 1041 |
+
|
| 1042 |
+
print(IpModel(ip='127.0.0.1'))
|
| 1043 |
+
#> ip=IPv4Address('127.0.0.1')
|
| 1044 |
+
|
| 1045 |
+
try:
|
| 1046 |
+
IpModel(ip='http://www.example.com')
|
| 1047 |
+
except ValueError as e:
|
| 1048 |
+
print(e.errors())
|
| 1049 |
+
'''
|
| 1050 |
+
[
|
| 1051 |
+
{
|
| 1052 |
+
'type': 'ip_any_address',
|
| 1053 |
+
'loc': ('ip',),
|
| 1054 |
+
'msg': 'value is not a valid IPv4 or IPv6 address',
|
| 1055 |
+
'input': 'http://www.example.com',
|
| 1056 |
+
}
|
| 1057 |
+
]
|
| 1058 |
+
'''
|
| 1059 |
+
```
|
| 1060 |
+
"""
|
| 1061 |
+
|
| 1062 |
+
__slots__ = ()
|
| 1063 |
+
|
| 1064 |
+
def __new__(cls, value: Any) -> IPvAnyAddressType:
|
| 1065 |
+
"""Validate an IPv4 or IPv6 address."""
|
| 1066 |
+
try:
|
| 1067 |
+
return IPv4Address(value)
|
| 1068 |
+
except ValueError:
|
| 1069 |
+
pass
|
| 1070 |
+
|
| 1071 |
+
try:
|
| 1072 |
+
return IPv6Address(value)
|
| 1073 |
+
except ValueError:
|
| 1074 |
+
raise PydanticCustomError('ip_any_address', 'value is not a valid IPv4 or IPv6 address')
|
| 1075 |
+
|
| 1076 |
+
@classmethod
|
| 1077 |
+
def __get_pydantic_json_schema__(
|
| 1078 |
+
cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler
|
| 1079 |
+
) -> JsonSchemaValue:
|
| 1080 |
+
field_schema = {}
|
| 1081 |
+
field_schema.update(type='string', format='ipvanyaddress')
|
| 1082 |
+
return field_schema
|
| 1083 |
+
|
| 1084 |
+
@classmethod
|
| 1085 |
+
def __get_pydantic_core_schema__(
|
| 1086 |
+
cls,
|
| 1087 |
+
_source: type[Any],
|
| 1088 |
+
_handler: GetCoreSchemaHandler,
|
| 1089 |
+
) -> core_schema.CoreSchema:
|
| 1090 |
+
return core_schema.no_info_plain_validator_function(
|
| 1091 |
+
cls._validate, serialization=core_schema.to_string_ser_schema()
|
| 1092 |
+
)
|
| 1093 |
+
|
| 1094 |
+
@classmethod
|
| 1095 |
+
def _validate(cls, input_value: Any, /) -> IPvAnyAddressType:
|
| 1096 |
+
return cls(input_value) # type: ignore[return-value]
|
| 1097 |
+
|
| 1098 |
+
class IPvAnyInterface:
|
| 1099 |
+
"""Validate an IPv4 or IPv6 interface."""
|
| 1100 |
+
|
| 1101 |
+
__slots__ = ()
|
| 1102 |
+
|
| 1103 |
+
def __new__(cls, value: NetworkType) -> IPvAnyInterfaceType:
|
| 1104 |
+
"""Validate an IPv4 or IPv6 interface."""
|
| 1105 |
+
try:
|
| 1106 |
+
return IPv4Interface(value)
|
| 1107 |
+
except ValueError:
|
| 1108 |
+
pass
|
| 1109 |
+
|
| 1110 |
+
try:
|
| 1111 |
+
return IPv6Interface(value)
|
| 1112 |
+
except ValueError:
|
| 1113 |
+
raise PydanticCustomError('ip_any_interface', 'value is not a valid IPv4 or IPv6 interface')
|
| 1114 |
+
|
| 1115 |
+
@classmethod
|
| 1116 |
+
def __get_pydantic_json_schema__(
|
| 1117 |
+
cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler
|
| 1118 |
+
) -> JsonSchemaValue:
|
| 1119 |
+
field_schema = {}
|
| 1120 |
+
field_schema.update(type='string', format='ipvanyinterface')
|
| 1121 |
+
return field_schema
|
| 1122 |
+
|
| 1123 |
+
@classmethod
|
| 1124 |
+
def __get_pydantic_core_schema__(
|
| 1125 |
+
cls,
|
| 1126 |
+
_source: type[Any],
|
| 1127 |
+
_handler: GetCoreSchemaHandler,
|
| 1128 |
+
) -> core_schema.CoreSchema:
|
| 1129 |
+
return core_schema.no_info_plain_validator_function(
|
| 1130 |
+
cls._validate, serialization=core_schema.to_string_ser_schema()
|
| 1131 |
+
)
|
| 1132 |
+
|
| 1133 |
+
@classmethod
|
| 1134 |
+
def _validate(cls, input_value: NetworkType, /) -> IPvAnyInterfaceType:
|
| 1135 |
+
return cls(input_value) # type: ignore[return-value]
|
| 1136 |
+
|
| 1137 |
+
class IPvAnyNetwork:
|
| 1138 |
+
"""Validate an IPv4 or IPv6 network."""
|
| 1139 |
+
|
| 1140 |
+
__slots__ = ()
|
| 1141 |
+
|
| 1142 |
+
def __new__(cls, value: NetworkType) -> IPvAnyNetworkType:
|
| 1143 |
+
"""Validate an IPv4 or IPv6 network."""
|
| 1144 |
+
# Assume IP Network is defined with a default value for `strict` argument.
|
| 1145 |
+
# Define your own class if you want to specify network address check strictness.
|
| 1146 |
+
try:
|
| 1147 |
+
return IPv4Network(value)
|
| 1148 |
+
except ValueError:
|
| 1149 |
+
pass
|
| 1150 |
+
|
| 1151 |
+
try:
|
| 1152 |
+
return IPv6Network(value)
|
| 1153 |
+
except ValueError:
|
| 1154 |
+
raise PydanticCustomError('ip_any_network', 'value is not a valid IPv4 or IPv6 network')
|
| 1155 |
+
|
| 1156 |
+
@classmethod
|
| 1157 |
+
def __get_pydantic_json_schema__(
|
| 1158 |
+
cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler
|
| 1159 |
+
) -> JsonSchemaValue:
|
| 1160 |
+
field_schema = {}
|
| 1161 |
+
field_schema.update(type='string', format='ipvanynetwork')
|
| 1162 |
+
return field_schema
|
| 1163 |
+
|
| 1164 |
+
@classmethod
|
| 1165 |
+
def __get_pydantic_core_schema__(
|
| 1166 |
+
cls,
|
| 1167 |
+
_source: type[Any],
|
| 1168 |
+
_handler: GetCoreSchemaHandler,
|
| 1169 |
+
) -> core_schema.CoreSchema:
|
| 1170 |
+
return core_schema.no_info_plain_validator_function(
|
| 1171 |
+
cls._validate, serialization=core_schema.to_string_ser_schema()
|
| 1172 |
+
)
|
| 1173 |
+
|
| 1174 |
+
@classmethod
|
| 1175 |
+
def _validate(cls, input_value: NetworkType, /) -> IPvAnyNetworkType:
|
| 1176 |
+
return cls(input_value) # type: ignore[return-value]
|
| 1177 |
+
|
| 1178 |
+
|
| 1179 |
+
def _build_pretty_email_regex() -> re.Pattern[str]:
|
| 1180 |
+
name_chars = r'[\w!#$%&\'*+\-/=?^_`{|}~]'
|
| 1181 |
+
unquoted_name_group = rf'((?:{name_chars}+\s+)*{name_chars}+)'
|
| 1182 |
+
quoted_name_group = r'"((?:[^"]|\")+)"'
|
| 1183 |
+
email_group = r'<(.+)>'
|
| 1184 |
+
return re.compile(rf'\s*(?:{unquoted_name_group}|{quoted_name_group})?\s*{email_group}\s*')
|
| 1185 |
+
|
| 1186 |
+
|
| 1187 |
+
pretty_email_regex = _build_pretty_email_regex()
|
| 1188 |
+
|
| 1189 |
+
MAX_EMAIL_LENGTH = 2048
|
| 1190 |
+
"""Maximum length for an email.
|
| 1191 |
+
A somewhat arbitrary but very generous number compared to what is allowed by most implementations.
|
| 1192 |
+
"""
|
| 1193 |
+
|
| 1194 |
+
|
| 1195 |
+
def validate_email(value: str) -> tuple[str, str]:
|
| 1196 |
+
"""Email address validation using [email-validator](https://pypi.org/project/email-validator/).
|
| 1197 |
+
|
| 1198 |
+
Returns:
|
| 1199 |
+
A tuple containing the local part of the email (or the name for "pretty" email addresses)
|
| 1200 |
+
and the normalized email.
|
| 1201 |
+
|
| 1202 |
+
Raises:
|
| 1203 |
+
PydanticCustomError: If the email is invalid.
|
| 1204 |
+
|
| 1205 |
+
Note:
|
| 1206 |
+
Note that:
|
| 1207 |
+
|
| 1208 |
+
* Raw IP address (literal) domain parts are not allowed.
|
| 1209 |
+
* `"John Doe <local_part@domain.com>"` style "pretty" email addresses are processed.
|
| 1210 |
+
* Spaces are striped from the beginning and end of addresses, but no error is raised.
|
| 1211 |
+
"""
|
| 1212 |
+
if email_validator is None:
|
| 1213 |
+
import_email_validator()
|
| 1214 |
+
|
| 1215 |
+
if len(value) > MAX_EMAIL_LENGTH:
|
| 1216 |
+
raise PydanticCustomError(
|
| 1217 |
+
'value_error',
|
| 1218 |
+
'value is not a valid email address: {reason}',
|
| 1219 |
+
{'reason': f'Length must not exceed {MAX_EMAIL_LENGTH} characters'},
|
| 1220 |
+
)
|
| 1221 |
+
|
| 1222 |
+
m = pretty_email_regex.fullmatch(value)
|
| 1223 |
+
name: str | None = None
|
| 1224 |
+
if m:
|
| 1225 |
+
unquoted_name, quoted_name, value = m.groups()
|
| 1226 |
+
name = unquoted_name or quoted_name
|
| 1227 |
+
|
| 1228 |
+
email = value.strip()
|
| 1229 |
+
|
| 1230 |
+
try:
|
| 1231 |
+
parts = email_validator.validate_email(email, check_deliverability=False)
|
| 1232 |
+
except email_validator.EmailNotValidError as e:
|
| 1233 |
+
raise PydanticCustomError(
|
| 1234 |
+
'value_error', 'value is not a valid email address: {reason}', {'reason': str(e.args[0])}
|
| 1235 |
+
) from e
|
| 1236 |
+
|
| 1237 |
+
email = parts.normalized
|
| 1238 |
+
assert email is not None
|
| 1239 |
+
name = name or parts.local_part
|
| 1240 |
+
return name, email
|
| 1241 |
+
|
| 1242 |
+
|
| 1243 |
+
__getattr__ = getattr_migration(__name__)
|
vllm/lib/python3.10/site-packages/pydantic/py.typed
ADDED
|
File without changes
|
vllm/lib/python3.10/site-packages/pydantic/root_model.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RootModel class and type definitions."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations as _annotations
|
| 4 |
+
|
| 5 |
+
import typing
|
| 6 |
+
from copy import copy, deepcopy
|
| 7 |
+
|
| 8 |
+
from pydantic_core import PydanticUndefined
|
| 9 |
+
|
| 10 |
+
from . import PydanticUserError
|
| 11 |
+
from ._internal import _model_construction, _repr
|
| 12 |
+
from .main import BaseModel, _object_setattr
|
| 13 |
+
|
| 14 |
+
if typing.TYPE_CHECKING:
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
from typing_extensions import Literal, Self, dataclass_transform
|
| 18 |
+
|
| 19 |
+
from .fields import Field as PydanticModelField
|
| 20 |
+
from .fields import PrivateAttr as PydanticModelPrivateAttr
|
| 21 |
+
|
| 22 |
+
# dataclass_transform could be applied to RootModel directly, but `ModelMetaclass`'s dataclass_transform
|
| 23 |
+
# takes priority (at least with pyright). We trick type checkers into thinking we apply dataclass_transform
|
| 24 |
+
# on a new metaclass.
|
| 25 |
+
@dataclass_transform(kw_only_default=False, field_specifiers=(PydanticModelField, PydanticModelPrivateAttr))
|
| 26 |
+
class _RootModelMetaclass(_model_construction.ModelMetaclass): ...
|
| 27 |
+
else:
|
| 28 |
+
_RootModelMetaclass = _model_construction.ModelMetaclass
|
| 29 |
+
|
| 30 |
+
__all__ = ('RootModel',)
|
| 31 |
+
|
| 32 |
+
RootModelRootType = typing.TypeVar('RootModelRootType')
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class RootModel(BaseModel, typing.Generic[RootModelRootType], metaclass=_RootModelMetaclass):
|
| 36 |
+
"""Usage docs: https://docs.pydantic.dev/2.10/concepts/models/#rootmodel-and-custom-root-types
|
| 37 |
+
|
| 38 |
+
A Pydantic `BaseModel` for the root object of the model.
|
| 39 |
+
|
| 40 |
+
Attributes:
|
| 41 |
+
root: The root object of the model.
|
| 42 |
+
__pydantic_root_model__: Whether the model is a RootModel.
|
| 43 |
+
__pydantic_private__: Private fields in the model.
|
| 44 |
+
__pydantic_extra__: Extra fields in the model.
|
| 45 |
+
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
__pydantic_root_model__ = True
|
| 49 |
+
__pydantic_private__ = None
|
| 50 |
+
__pydantic_extra__ = None
|
| 51 |
+
|
| 52 |
+
root: RootModelRootType
|
| 53 |
+
|
| 54 |
+
def __init_subclass__(cls, **kwargs):
|
| 55 |
+
extra = cls.model_config.get('extra')
|
| 56 |
+
if extra is not None:
|
| 57 |
+
raise PydanticUserError(
|
| 58 |
+
"`RootModel` does not support setting `model_config['extra']`", code='root-model-extra'
|
| 59 |
+
)
|
| 60 |
+
super().__init_subclass__(**kwargs)
|
| 61 |
+
|
| 62 |
+
def __init__(self, /, root: RootModelRootType = PydanticUndefined, **data) -> None: # type: ignore
|
| 63 |
+
__tracebackhide__ = True
|
| 64 |
+
if data:
|
| 65 |
+
if root is not PydanticUndefined:
|
| 66 |
+
raise ValueError(
|
| 67 |
+
'"RootModel.__init__" accepts either a single positional argument or arbitrary keyword arguments'
|
| 68 |
+
)
|
| 69 |
+
root = data # type: ignore
|
| 70 |
+
self.__pydantic_validator__.validate_python(root, self_instance=self)
|
| 71 |
+
|
| 72 |
+
__init__.__pydantic_base_init__ = True # pyright: ignore[reportFunctionMemberAccess]
|
| 73 |
+
|
| 74 |
+
@classmethod
|
| 75 |
+
def model_construct(cls, root: RootModelRootType, _fields_set: set[str] | None = None) -> Self: # type: ignore
|
| 76 |
+
"""Create a new model using the provided root object and update fields set.
|
| 77 |
+
|
| 78 |
+
Args:
|
| 79 |
+
root: The root object of the model.
|
| 80 |
+
_fields_set: The set of fields to be updated.
|
| 81 |
+
|
| 82 |
+
Returns:
|
| 83 |
+
The new model.
|
| 84 |
+
|
| 85 |
+
Raises:
|
| 86 |
+
NotImplemented: If the model is not a subclass of `RootModel`.
|
| 87 |
+
"""
|
| 88 |
+
return super().model_construct(root=root, _fields_set=_fields_set)
|
| 89 |
+
|
| 90 |
+
def __getstate__(self) -> dict[Any, Any]:
|
| 91 |
+
return {
|
| 92 |
+
'__dict__': self.__dict__,
|
| 93 |
+
'__pydantic_fields_set__': self.__pydantic_fields_set__,
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
def __setstate__(self, state: dict[Any, Any]) -> None:
|
| 97 |
+
_object_setattr(self, '__pydantic_fields_set__', state['__pydantic_fields_set__'])
|
| 98 |
+
_object_setattr(self, '__dict__', state['__dict__'])
|
| 99 |
+
|
| 100 |
+
def __copy__(self) -> Self:
|
| 101 |
+
"""Returns a shallow copy of the model."""
|
| 102 |
+
cls = type(self)
|
| 103 |
+
m = cls.__new__(cls)
|
| 104 |
+
_object_setattr(m, '__dict__', copy(self.__dict__))
|
| 105 |
+
_object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))
|
| 106 |
+
return m
|
| 107 |
+
|
| 108 |
+
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
|
| 109 |
+
"""Returns a deep copy of the model."""
|
| 110 |
+
cls = type(self)
|
| 111 |
+
m = cls.__new__(cls)
|
| 112 |
+
_object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
|
| 113 |
+
# This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
|
| 114 |
+
# and attempting a deepcopy would be marginally slower.
|
| 115 |
+
_object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))
|
| 116 |
+
return m
|
| 117 |
+
|
| 118 |
+
if typing.TYPE_CHECKING:
|
| 119 |
+
|
| 120 |
+
def model_dump( # type: ignore
|
| 121 |
+
self,
|
| 122 |
+
*,
|
| 123 |
+
mode: Literal['json', 'python'] | str = 'python',
|
| 124 |
+
include: Any = None,
|
| 125 |
+
exclude: Any = None,
|
| 126 |
+
context: dict[str, Any] | None = None,
|
| 127 |
+
by_alias: bool = False,
|
| 128 |
+
exclude_unset: bool = False,
|
| 129 |
+
exclude_defaults: bool = False,
|
| 130 |
+
exclude_none: bool = False,
|
| 131 |
+
round_trip: bool = False,
|
| 132 |
+
warnings: bool | Literal['none', 'warn', 'error'] = True,
|
| 133 |
+
serialize_as_any: bool = False,
|
| 134 |
+
) -> Any:
|
| 135 |
+
"""This method is included just to get a more accurate return type for type checkers.
|
| 136 |
+
It is included in this `if TYPE_CHECKING:` block since no override is actually necessary.
|
| 137 |
+
|
| 138 |
+
See the documentation of `BaseModel.model_dump` for more details about the arguments.
|
| 139 |
+
|
| 140 |
+
Generally, this method will have a return type of `RootModelRootType`, assuming that `RootModelRootType` is
|
| 141 |
+
not a `BaseModel` subclass. If `RootModelRootType` is a `BaseModel` subclass, then the return
|
| 142 |
+
type will likely be `dict[str, Any]`, as `model_dump` calls are recursive. The return type could
|
| 143 |
+
even be something different, in the case of a custom serializer.
|
| 144 |
+
Thus, `Any` is used here to catch all of these cases.
|
| 145 |
+
"""
|
| 146 |
+
...
|
| 147 |
+
|
| 148 |
+
def __eq__(self, other: Any) -> bool:
|
| 149 |
+
if not isinstance(other, RootModel):
|
| 150 |
+
return NotImplemented
|
| 151 |
+
return self.__pydantic_fields__['root'].annotation == other.__pydantic_fields__[
|
| 152 |
+
'root'
|
| 153 |
+
].annotation and super().__eq__(other)
|
| 154 |
+
|
| 155 |
+
def __repr_args__(self) -> _repr.ReprArgs:
|
| 156 |
+
yield 'root', self.root
|
vllm/lib/python3.10/site-packages/pydantic/schema.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The `schema` module is a backport module from V1."""
|
| 2 |
+
|
| 3 |
+
from ._migration import getattr_migration
|
| 4 |
+
|
| 5 |
+
__getattr__ = getattr_migration(__name__)
|
vllm/lib/python3.10/site-packages/pydantic/tools.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The `tools` module is a backport module from V1."""
|
| 2 |
+
|
| 3 |
+
from ._migration import getattr_migration
|
| 4 |
+
|
| 5 |
+
__getattr__ = getattr_migration(__name__)
|
vllm/lib/python3.10/site-packages/pydantic/types.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
vllm/lib/python3.10/site-packages/pydantic/typing.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""`typing` module is a backport module from V1."""
|
| 2 |
+
|
| 3 |
+
from ._migration import getattr_migration
|
| 4 |
+
|
| 5 |
+
__getattr__ = getattr_migration(__name__)
|
vllm/lib/python3.10/site-packages/pydantic/utils.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The `utils` module is a backport module from V1."""
|
| 2 |
+
|
| 3 |
+
from ._migration import getattr_migration
|
| 4 |
+
|
| 5 |
+
__getattr__ = getattr_migration(__name__)
|
vllm/lib/python3.10/site-packages/pydantic/v1/__init__.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa
|
| 2 |
+
from pydantic.v1 import dataclasses
|
| 3 |
+
from pydantic.v1.annotated_types import create_model_from_namedtuple, create_model_from_typeddict
|
| 4 |
+
from pydantic.v1.class_validators import root_validator, validator
|
| 5 |
+
from pydantic.v1.config import BaseConfig, ConfigDict, Extra
|
| 6 |
+
from pydantic.v1.decorator import validate_arguments
|
| 7 |
+
from pydantic.v1.env_settings import BaseSettings
|
| 8 |
+
from pydantic.v1.error_wrappers import ValidationError
|
| 9 |
+
from pydantic.v1.errors import *
|
| 10 |
+
from pydantic.v1.fields import Field, PrivateAttr, Required
|
| 11 |
+
from pydantic.v1.main import *
|
| 12 |
+
from pydantic.v1.networks import *
|
| 13 |
+
from pydantic.v1.parse import Protocol
|
| 14 |
+
from pydantic.v1.tools import *
|
| 15 |
+
from pydantic.v1.types import *
|
| 16 |
+
from pydantic.v1.version import VERSION, compiled
|
| 17 |
+
|
| 18 |
+
__version__ = VERSION
|
| 19 |
+
|
| 20 |
+
# WARNING __all__ from pydantic.errors is not included here, it will be removed as an export here in v2
|
| 21 |
+
# please use "from pydantic.v1.errors import ..." instead
|
| 22 |
+
__all__ = [
|
| 23 |
+
# annotated types utils
|
| 24 |
+
'create_model_from_namedtuple',
|
| 25 |
+
'create_model_from_typeddict',
|
| 26 |
+
# dataclasses
|
| 27 |
+
'dataclasses',
|
| 28 |
+
# class_validators
|
| 29 |
+
'root_validator',
|
| 30 |
+
'validator',
|
| 31 |
+
# config
|
| 32 |
+
'BaseConfig',
|
| 33 |
+
'ConfigDict',
|
| 34 |
+
'Extra',
|
| 35 |
+
# decorator
|
| 36 |
+
'validate_arguments',
|
| 37 |
+
# env_settings
|
| 38 |
+
'BaseSettings',
|
| 39 |
+
# error_wrappers
|
| 40 |
+
'ValidationError',
|
| 41 |
+
# fields
|
| 42 |
+
'Field',
|
| 43 |
+
'Required',
|
| 44 |
+
# main
|
| 45 |
+
'BaseModel',
|
| 46 |
+
'create_model',
|
| 47 |
+
'validate_model',
|
| 48 |
+
# network
|
| 49 |
+
'AnyUrl',
|
| 50 |
+
'AnyHttpUrl',
|
| 51 |
+
'FileUrl',
|
| 52 |
+
'HttpUrl',
|
| 53 |
+
'stricturl',
|
| 54 |
+
'EmailStr',
|
| 55 |
+
'NameEmail',
|
| 56 |
+
'IPvAnyAddress',
|
| 57 |
+
'IPvAnyInterface',
|
| 58 |
+
'IPvAnyNetwork',
|
| 59 |
+
'PostgresDsn',
|
| 60 |
+
'CockroachDsn',
|
| 61 |
+
'AmqpDsn',
|
| 62 |
+
'RedisDsn',
|
| 63 |
+
'MongoDsn',
|
| 64 |
+
'KafkaDsn',
|
| 65 |
+
'validate_email',
|
| 66 |
+
# parse
|
| 67 |
+
'Protocol',
|
| 68 |
+
# tools
|
| 69 |
+
'parse_file_as',
|
| 70 |
+
'parse_obj_as',
|
| 71 |
+
'parse_raw_as',
|
| 72 |
+
'schema_of',
|
| 73 |
+
'schema_json_of',
|
| 74 |
+
# types
|
| 75 |
+
'NoneStr',
|
| 76 |
+
'NoneBytes',
|
| 77 |
+
'StrBytes',
|
| 78 |
+
'NoneStrBytes',
|
| 79 |
+
'StrictStr',
|
| 80 |
+
'ConstrainedBytes',
|
| 81 |
+
'conbytes',
|
| 82 |
+
'ConstrainedList',
|
| 83 |
+
'conlist',
|
| 84 |
+
'ConstrainedSet',
|
| 85 |
+
'conset',
|
| 86 |
+
'ConstrainedFrozenSet',
|
| 87 |
+
'confrozenset',
|
| 88 |
+
'ConstrainedStr',
|
| 89 |
+
'constr',
|
| 90 |
+
'PyObject',
|
| 91 |
+
'ConstrainedInt',
|
| 92 |
+
'conint',
|
| 93 |
+
'PositiveInt',
|
| 94 |
+
'NegativeInt',
|
| 95 |
+
'NonNegativeInt',
|
| 96 |
+
'NonPositiveInt',
|
| 97 |
+
'ConstrainedFloat',
|
| 98 |
+
'confloat',
|
| 99 |
+
'PositiveFloat',
|
| 100 |
+
'NegativeFloat',
|
| 101 |
+
'NonNegativeFloat',
|
| 102 |
+
'NonPositiveFloat',
|
| 103 |
+
'FiniteFloat',
|
| 104 |
+
'ConstrainedDecimal',
|
| 105 |
+
'condecimal',
|
| 106 |
+
'ConstrainedDate',
|
| 107 |
+
'condate',
|
| 108 |
+
'UUID1',
|
| 109 |
+
'UUID3',
|
| 110 |
+
'UUID4',
|
| 111 |
+
'UUID5',
|
| 112 |
+
'FilePath',
|
| 113 |
+
'DirectoryPath',
|
| 114 |
+
'Json',
|
| 115 |
+
'JsonWrapper',
|
| 116 |
+
'SecretField',
|
| 117 |
+
'SecretStr',
|
| 118 |
+
'SecretBytes',
|
| 119 |
+
'StrictBool',
|
| 120 |
+
'StrictBytes',
|
| 121 |
+
'StrictInt',
|
| 122 |
+
'StrictFloat',
|
| 123 |
+
'PaymentCardNumber',
|
| 124 |
+
'PrivateAttr',
|
| 125 |
+
'ByteSize',
|
| 126 |
+
'PastDate',
|
| 127 |
+
'FutureDate',
|
| 128 |
+
# version
|
| 129 |
+
'compiled',
|
| 130 |
+
'VERSION',
|
| 131 |
+
]
|