Загрузить файлы в «venv/Lib/site-packages/pydantic»

This commit is contained in:
2026-07-02 20:05:33 +00:00
parent 4aeb54f24d
commit 474c48492c
5 changed files with 1091 additions and 0 deletions

View File

@@ -0,0 +1,456 @@
from importlib import import_module
from typing import TYPE_CHECKING
from warnings import warn
from ._migration import getattr_migration
from .version import VERSION, _ensure_pydantic_core_version
_ensure_pydantic_core_version()
del _ensure_pydantic_core_version
if TYPE_CHECKING:
# import of virtually everything is supported via `__getattr__` below,
# but we need them here for type checking and IDE support
import pydantic_core
from pydantic_core.core_schema import (
FieldSerializationInfo,
SerializationInfo,
SerializerFunctionWrapHandler,
ValidationInfo,
ValidatorFunctionWrapHandler,
)
from . import dataclasses
from .aliases import AliasChoices, AliasGenerator, AliasPath
from .annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler
from .config import ConfigDict, with_config
from .errors import *
from .fields import Field, PrivateAttr, computed_field
from .functional_serializers import (
PlainSerializer,
SerializeAsAny,
WrapSerializer,
field_serializer,
model_serializer,
)
from .functional_validators import (
AfterValidator,
BeforeValidator,
InstanceOf,
ModelWrapValidatorHandler,
PlainValidator,
SkipValidation,
ValidateAs,
WrapValidator,
field_validator,
model_validator,
)
from .json_schema import WithJsonSchema
from .main import *
from .networks import *
from .type_adapter import TypeAdapter
from .types import *
from .validate_call_decorator import validate_call
from .warnings import (
PydanticDeprecatedSince20,
PydanticDeprecatedSince26,
PydanticDeprecatedSince29,
PydanticDeprecatedSince210,
PydanticDeprecatedSince211,
PydanticDeprecatedSince212,
PydanticDeprecationWarning,
PydanticExperimentalWarning,
)
# this encourages pycharm to import `ValidationError` from here, not pydantic_core
ValidationError = pydantic_core.ValidationError
from .deprecated.class_validators import root_validator, validator
from .deprecated.config import BaseConfig, Extra
from .deprecated.tools import *
from .root_model import RootModel
__version__ = VERSION
__all__ = (
# dataclasses
'dataclasses',
# functional validators
'field_validator',
'model_validator',
'AfterValidator',
'BeforeValidator',
'PlainValidator',
'WrapValidator',
'SkipValidation',
'ValidateAs',
'InstanceOf',
'ModelWrapValidatorHandler',
# JSON Schema
'WithJsonSchema',
# deprecated V1 functional validators, these are imported via `__getattr__` below
'root_validator',
'validator',
# functional serializers
'field_serializer',
'model_serializer',
'PlainSerializer',
'SerializeAsAny',
'WrapSerializer',
# config
'ConfigDict',
'with_config',
# deprecated V1 config, these are imported via `__getattr__` below
'BaseConfig',
'Extra',
# validate_call
'validate_call',
# errors
'PydanticErrorCodes',
'PydanticUserError',
'PydanticSchemaGenerationError',
'PydanticImportError',
'PydanticUndefinedAnnotation',
'PydanticInvalidForJsonSchema',
'PydanticForbiddenQualifier',
# fields
'Field',
'computed_field',
'PrivateAttr',
# alias
'AliasChoices',
'AliasGenerator',
'AliasPath',
# main
'BaseModel',
'create_model',
# network
'AnyUrl',
'AnyHttpUrl',
'FileUrl',
'HttpUrl',
'FtpUrl',
'WebsocketUrl',
'AnyWebsocketUrl',
'UrlConstraints',
'EmailStr',
'NameEmail',
'IPvAnyAddress',
'IPvAnyInterface',
'IPvAnyNetwork',
'PostgresDsn',
'CockroachDsn',
'AmqpDsn',
'RedisDsn',
'MongoDsn',
'KafkaDsn',
'NatsDsn',
'MySQLDsn',
'MariaDBDsn',
'ClickHouseDsn',
'SnowflakeDsn',
'validate_email',
# root_model
'RootModel',
# deprecated tools, these are imported via `__getattr__` below
'parse_obj_as',
'schema_of',
'schema_json_of',
# types
'Strict',
'StrictStr',
'conbytes',
'conlist',
'conset',
'confrozenset',
'constr',
'StringConstraints',
'ImportString',
'conint',
'PositiveInt',
'NegativeInt',
'NonNegativeInt',
'NonPositiveInt',
'confloat',
'PositiveFloat',
'NegativeFloat',
'NonNegativeFloat',
'NonPositiveFloat',
'FiniteFloat',
'condecimal',
'condate',
'UUID1',
'UUID3',
'UUID4',
'UUID5',
'UUID6',
'UUID7',
'UUID8',
'FilePath',
'DirectoryPath',
'NewPath',
'Json',
'Secret',
'SecretStr',
'SecretBytes',
'SocketPath',
'StrictBool',
'StrictBytes',
'StrictInt',
'StrictFloat',
'PaymentCardNumber',
'ByteSize',
'PastDate',
'FutureDate',
'PastDatetime',
'FutureDatetime',
'AwareDatetime',
'NaiveDatetime',
'AllowInfNan',
'EncoderProtocol',
'EncodedBytes',
'EncodedStr',
'Base64Encoder',
'Base64Bytes',
'Base64Str',
'Base64UrlBytes',
'Base64UrlStr',
'GetPydanticSchema',
'Tag',
'Discriminator',
'JsonValue',
'FailFast',
# type_adapter
'TypeAdapter',
# version
'__version__',
'VERSION',
# warnings
'PydanticDeprecatedSince20',
'PydanticDeprecatedSince26',
'PydanticDeprecatedSince29',
'PydanticDeprecatedSince210',
'PydanticDeprecatedSince211',
'PydanticDeprecatedSince212',
'PydanticDeprecationWarning',
'PydanticExperimentalWarning',
# annotated handlers
'GetCoreSchemaHandler',
'GetJsonSchemaHandler',
# pydantic_core
'ValidationError',
'ValidationInfo',
'SerializationInfo',
'ValidatorFunctionWrapHandler',
'FieldSerializationInfo',
'SerializerFunctionWrapHandler',
'OnErrorOmit',
)
# A mapping of {<member name>: (package, <module name>)} defining dynamic imports
_dynamic_imports: 'dict[str, tuple[str, str]]' = {
'dataclasses': (__spec__.parent, '__module__'),
# functional validators
'field_validator': (__spec__.parent, '.functional_validators'),
'model_validator': (__spec__.parent, '.functional_validators'),
'AfterValidator': (__spec__.parent, '.functional_validators'),
'BeforeValidator': (__spec__.parent, '.functional_validators'),
'PlainValidator': (__spec__.parent, '.functional_validators'),
'WrapValidator': (__spec__.parent, '.functional_validators'),
'SkipValidation': (__spec__.parent, '.functional_validators'),
'InstanceOf': (__spec__.parent, '.functional_validators'),
'ValidateAs': (__spec__.parent, '.functional_validators'),
'ModelWrapValidatorHandler': (__spec__.parent, '.functional_validators'),
# JSON Schema
'WithJsonSchema': (__spec__.parent, '.json_schema'),
# functional serializers
'field_serializer': (__spec__.parent, '.functional_serializers'),
'model_serializer': (__spec__.parent, '.functional_serializers'),
'PlainSerializer': (__spec__.parent, '.functional_serializers'),
'SerializeAsAny': (__spec__.parent, '.functional_serializers'),
'WrapSerializer': (__spec__.parent, '.functional_serializers'),
# config
'ConfigDict': (__spec__.parent, '.config'),
'with_config': (__spec__.parent, '.config'),
# validate call
'validate_call': (__spec__.parent, '.validate_call_decorator'),
# errors
'PydanticErrorCodes': (__spec__.parent, '.errors'),
'PydanticUserError': (__spec__.parent, '.errors'),
'PydanticSchemaGenerationError': (__spec__.parent, '.errors'),
'PydanticImportError': (__spec__.parent, '.errors'),
'PydanticUndefinedAnnotation': (__spec__.parent, '.errors'),
'PydanticInvalidForJsonSchema': (__spec__.parent, '.errors'),
'PydanticForbiddenQualifier': (__spec__.parent, '.errors'),
# fields
'Field': (__spec__.parent, '.fields'),
'computed_field': (__spec__.parent, '.fields'),
'PrivateAttr': (__spec__.parent, '.fields'),
# alias
'AliasChoices': (__spec__.parent, '.aliases'),
'AliasGenerator': (__spec__.parent, '.aliases'),
'AliasPath': (__spec__.parent, '.aliases'),
# main
'BaseModel': (__spec__.parent, '.main'),
'create_model': (__spec__.parent, '.main'),
# network
'AnyUrl': (__spec__.parent, '.networks'),
'AnyHttpUrl': (__spec__.parent, '.networks'),
'FileUrl': (__spec__.parent, '.networks'),
'HttpUrl': (__spec__.parent, '.networks'),
'FtpUrl': (__spec__.parent, '.networks'),
'WebsocketUrl': (__spec__.parent, '.networks'),
'AnyWebsocketUrl': (__spec__.parent, '.networks'),
'UrlConstraints': (__spec__.parent, '.networks'),
'EmailStr': (__spec__.parent, '.networks'),
'NameEmail': (__spec__.parent, '.networks'),
'IPvAnyAddress': (__spec__.parent, '.networks'),
'IPvAnyInterface': (__spec__.parent, '.networks'),
'IPvAnyNetwork': (__spec__.parent, '.networks'),
'PostgresDsn': (__spec__.parent, '.networks'),
'CockroachDsn': (__spec__.parent, '.networks'),
'AmqpDsn': (__spec__.parent, '.networks'),
'RedisDsn': (__spec__.parent, '.networks'),
'MongoDsn': (__spec__.parent, '.networks'),
'KafkaDsn': (__spec__.parent, '.networks'),
'NatsDsn': (__spec__.parent, '.networks'),
'MySQLDsn': (__spec__.parent, '.networks'),
'MariaDBDsn': (__spec__.parent, '.networks'),
'ClickHouseDsn': (__spec__.parent, '.networks'),
'SnowflakeDsn': (__spec__.parent, '.networks'),
'validate_email': (__spec__.parent, '.networks'),
# root_model
'RootModel': (__spec__.parent, '.root_model'),
# types
'Strict': (__spec__.parent, '.types'),
'StrictStr': (__spec__.parent, '.types'),
'conbytes': (__spec__.parent, '.types'),
'conlist': (__spec__.parent, '.types'),
'conset': (__spec__.parent, '.types'),
'confrozenset': (__spec__.parent, '.types'),
'constr': (__spec__.parent, '.types'),
'StringConstraints': (__spec__.parent, '.types'),
'ImportString': (__spec__.parent, '.types'),
'conint': (__spec__.parent, '.types'),
'PositiveInt': (__spec__.parent, '.types'),
'NegativeInt': (__spec__.parent, '.types'),
'NonNegativeInt': (__spec__.parent, '.types'),
'NonPositiveInt': (__spec__.parent, '.types'),
'confloat': (__spec__.parent, '.types'),
'PositiveFloat': (__spec__.parent, '.types'),
'NegativeFloat': (__spec__.parent, '.types'),
'NonNegativeFloat': (__spec__.parent, '.types'),
'NonPositiveFloat': (__spec__.parent, '.types'),
'FiniteFloat': (__spec__.parent, '.types'),
'condecimal': (__spec__.parent, '.types'),
'condate': (__spec__.parent, '.types'),
'UUID1': (__spec__.parent, '.types'),
'UUID3': (__spec__.parent, '.types'),
'UUID4': (__spec__.parent, '.types'),
'UUID5': (__spec__.parent, '.types'),
'UUID6': (__spec__.parent, '.types'),
'UUID7': (__spec__.parent, '.types'),
'UUID8': (__spec__.parent, '.types'),
'FilePath': (__spec__.parent, '.types'),
'DirectoryPath': (__spec__.parent, '.types'),
'NewPath': (__spec__.parent, '.types'),
'Json': (__spec__.parent, '.types'),
'Secret': (__spec__.parent, '.types'),
'SecretStr': (__spec__.parent, '.types'),
'SecretBytes': (__spec__.parent, '.types'),
'StrictBool': (__spec__.parent, '.types'),
'StrictBytes': (__spec__.parent, '.types'),
'StrictInt': (__spec__.parent, '.types'),
'StrictFloat': (__spec__.parent, '.types'),
'PaymentCardNumber': (__spec__.parent, '.types'),
'ByteSize': (__spec__.parent, '.types'),
'PastDate': (__spec__.parent, '.types'),
'SocketPath': (__spec__.parent, '.types'),
'FutureDate': (__spec__.parent, '.types'),
'PastDatetime': (__spec__.parent, '.types'),
'FutureDatetime': (__spec__.parent, '.types'),
'AwareDatetime': (__spec__.parent, '.types'),
'NaiveDatetime': (__spec__.parent, '.types'),
'AllowInfNan': (__spec__.parent, '.types'),
'EncoderProtocol': (__spec__.parent, '.types'),
'EncodedBytes': (__spec__.parent, '.types'),
'EncodedStr': (__spec__.parent, '.types'),
'Base64Encoder': (__spec__.parent, '.types'),
'Base64Bytes': (__spec__.parent, '.types'),
'Base64Str': (__spec__.parent, '.types'),
'Base64UrlBytes': (__spec__.parent, '.types'),
'Base64UrlStr': (__spec__.parent, '.types'),
'GetPydanticSchema': (__spec__.parent, '.types'),
'Tag': (__spec__.parent, '.types'),
'Discriminator': (__spec__.parent, '.types'),
'JsonValue': (__spec__.parent, '.types'),
'OnErrorOmit': (__spec__.parent, '.types'),
'FailFast': (__spec__.parent, '.types'),
# type_adapter
'TypeAdapter': (__spec__.parent, '.type_adapter'),
# warnings
'PydanticDeprecatedSince20': (__spec__.parent, '.warnings'),
'PydanticDeprecatedSince26': (__spec__.parent, '.warnings'),
'PydanticDeprecatedSince29': (__spec__.parent, '.warnings'),
'PydanticDeprecatedSince210': (__spec__.parent, '.warnings'),
'PydanticDeprecatedSince211': (__spec__.parent, '.warnings'),
'PydanticDeprecatedSince212': (__spec__.parent, '.warnings'),
'PydanticDeprecationWarning': (__spec__.parent, '.warnings'),
'PydanticExperimentalWarning': (__spec__.parent, '.warnings'),
# annotated handlers
'GetCoreSchemaHandler': (__spec__.parent, '.annotated_handlers'),
'GetJsonSchemaHandler': (__spec__.parent, '.annotated_handlers'),
# pydantic_core stuff
'ValidationError': ('pydantic_core', '.'),
'ValidationInfo': ('pydantic_core', '.core_schema'),
'SerializationInfo': ('pydantic_core', '.core_schema'),
'ValidatorFunctionWrapHandler': ('pydantic_core', '.core_schema'),
'FieldSerializationInfo': ('pydantic_core', '.core_schema'),
'SerializerFunctionWrapHandler': ('pydantic_core', '.core_schema'),
# deprecated, mostly not included in __all__
'root_validator': (__spec__.parent, '.deprecated.class_validators'),
'validator': (__spec__.parent, '.deprecated.class_validators'),
'BaseConfig': (__spec__.parent, '.deprecated.config'),
'Extra': (__spec__.parent, '.deprecated.config'),
'parse_obj_as': (__spec__.parent, '.deprecated.tools'),
'schema_of': (__spec__.parent, '.deprecated.tools'),
'schema_json_of': (__spec__.parent, '.deprecated.tools'),
# deprecated dynamic imports
'FieldValidationInfo': ('pydantic_core', '.core_schema'),
'GenerateSchema': (__spec__.parent, '._internal._generate_schema'),
}
_deprecated_dynamic_imports = {'FieldValidationInfo', 'GenerateSchema'}
_getattr_migration = getattr_migration(__name__)
def __getattr__(attr_name: str) -> object:
if attr_name in _deprecated_dynamic_imports:
from pydantic.warnings import PydanticDeprecatedSince20
warn(
f'Importing {attr_name} from `pydantic` is deprecated. This feature is either no longer supported, or is not public.',
PydanticDeprecatedSince20,
stacklevel=2,
)
dynamic_attr = _dynamic_imports.get(attr_name)
if dynamic_attr is None:
return _getattr_migration(attr_name)
package, module_name = dynamic_attr
if module_name == '__module__':
result = import_module(f'.{attr_name}', package=package)
globals()[attr_name] = result
return result
else:
module = import_module(module_name, package=package)
result = getattr(module, attr_name)
g = globals()
for k, (_, v_module_name) in _dynamic_imports.items():
if v_module_name == module_name and k not in _deprecated_dynamic_imports:
g[k] = getattr(module, k)
return result
def __dir__() -> list[str]:
return list(__all__)

View File

@@ -0,0 +1,316 @@
import sys
from typing import Any, Callable
from pydantic.warnings import PydanticDeprecatedSince20
from .version import version_short
MOVED_IN_V2 = {
'pydantic.utils:version_info': 'pydantic.version:version_info',
'pydantic.error_wrappers:ValidationError': 'pydantic:ValidationError',
'pydantic.utils:to_camel': 'pydantic.alias_generators:to_pascal',
'pydantic.utils:to_lower_camel': 'pydantic.alias_generators:to_camel',
'pydantic:PyObject': 'pydantic.types:ImportString',
'pydantic.types:PyObject': 'pydantic.types:ImportString',
'pydantic.generics:GenericModel': 'pydantic.BaseModel',
}
DEPRECATED_MOVED_IN_V2 = {
'pydantic.tools:schema_of': 'pydantic.deprecated.tools:schema_of',
'pydantic.tools:parse_obj_as': 'pydantic.deprecated.tools:parse_obj_as',
'pydantic.tools:schema_json_of': 'pydantic.deprecated.tools:schema_json_of',
'pydantic.json:pydantic_encoder': 'pydantic.deprecated.json:pydantic_encoder',
'pydantic:validate_arguments': 'pydantic.deprecated.decorator:validate_arguments',
'pydantic.json:custom_pydantic_encoder': 'pydantic.deprecated.json:custom_pydantic_encoder',
'pydantic.json:timedelta_isoformat': 'pydantic.deprecated.json:timedelta_isoformat',
'pydantic.decorator:validate_arguments': 'pydantic.deprecated.decorator:validate_arguments',
'pydantic.class_validators:validator': 'pydantic.deprecated.class_validators:validator',
'pydantic.class_validators:root_validator': 'pydantic.deprecated.class_validators:root_validator',
'pydantic.config:BaseConfig': 'pydantic.deprecated.config:BaseConfig',
'pydantic.config:Extra': 'pydantic.deprecated.config:Extra',
}
REDIRECT_TO_V1 = {
f'pydantic.utils:{obj}': f'pydantic.v1.utils:{obj}'
for obj in (
'deep_update',
'GetterDict',
'lenient_issubclass',
'lenient_isinstance',
'is_valid_field',
'update_not_none',
'import_string',
'Representation',
'ROOT_KEY',
'smart_deepcopy',
'sequence_like',
)
}
REMOVED_IN_V2 = {
'pydantic:ConstrainedBytes',
'pydantic:ConstrainedDate',
'pydantic:ConstrainedDecimal',
'pydantic:ConstrainedFloat',
'pydantic:ConstrainedFrozenSet',
'pydantic:ConstrainedInt',
'pydantic:ConstrainedList',
'pydantic:ConstrainedSet',
'pydantic:ConstrainedStr',
'pydantic:JsonWrapper',
'pydantic:NoneBytes',
'pydantic:NoneStr',
'pydantic:NoneStrBytes',
'pydantic:Protocol',
'pydantic:Required',
'pydantic:StrBytes',
'pydantic:compiled',
'pydantic.config:get_config',
'pydantic.config:inherit_config',
'pydantic.config:prepare_config',
'pydantic:create_model_from_namedtuple',
'pydantic:create_model_from_typeddict',
'pydantic.dataclasses:create_pydantic_model_from_dataclass',
'pydantic.dataclasses:make_dataclass_validator',
'pydantic.dataclasses:set_validation',
'pydantic.datetime_parse:parse_date',
'pydantic.datetime_parse:parse_time',
'pydantic.datetime_parse:parse_datetime',
'pydantic.datetime_parse:parse_duration',
'pydantic.error_wrappers:ErrorWrapper',
'pydantic.errors:AnyStrMaxLengthError',
'pydantic.errors:AnyStrMinLengthError',
'pydantic.errors:ArbitraryTypeError',
'pydantic.errors:BoolError',
'pydantic.errors:BytesError',
'pydantic.errors:CallableError',
'pydantic.errors:ClassError',
'pydantic.errors:ColorError',
'pydantic.errors:ConfigError',
'pydantic.errors:DataclassTypeError',
'pydantic.errors:DateError',
'pydantic.errors:DateNotInTheFutureError',
'pydantic.errors:DateNotInThePastError',
'pydantic.errors:DateTimeError',
'pydantic.errors:DecimalError',
'pydantic.errors:DecimalIsNotFiniteError',
'pydantic.errors:DecimalMaxDigitsError',
'pydantic.errors:DecimalMaxPlacesError',
'pydantic.errors:DecimalWholeDigitsError',
'pydantic.errors:DictError',
'pydantic.errors:DurationError',
'pydantic.errors:EmailError',
'pydantic.errors:EnumError',
'pydantic.errors:EnumMemberError',
'pydantic.errors:ExtraError',
'pydantic.errors:FloatError',
'pydantic.errors:FrozenSetError',
'pydantic.errors:FrozenSetMaxLengthError',
'pydantic.errors:FrozenSetMinLengthError',
'pydantic.errors:HashableError',
'pydantic.errors:IPv4AddressError',
'pydantic.errors:IPv4InterfaceError',
'pydantic.errors:IPv4NetworkError',
'pydantic.errors:IPv6AddressError',
'pydantic.errors:IPv6InterfaceError',
'pydantic.errors:IPv6NetworkError',
'pydantic.errors:IPvAnyAddressError',
'pydantic.errors:IPvAnyInterfaceError',
'pydantic.errors:IPvAnyNetworkError',
'pydantic.errors:IntEnumError',
'pydantic.errors:IntegerError',
'pydantic.errors:InvalidByteSize',
'pydantic.errors:InvalidByteSizeUnit',
'pydantic.errors:InvalidDiscriminator',
'pydantic.errors:InvalidLengthForBrand',
'pydantic.errors:JsonError',
'pydantic.errors:JsonTypeError',
'pydantic.errors:ListError',
'pydantic.errors:ListMaxLengthError',
'pydantic.errors:ListMinLengthError',
'pydantic.errors:ListUniqueItemsError',
'pydantic.errors:LuhnValidationError',
'pydantic.errors:MissingDiscriminator',
'pydantic.errors:MissingError',
'pydantic.errors:NoneIsAllowedError',
'pydantic.errors:NoneIsNotAllowedError',
'pydantic.errors:NotDigitError',
'pydantic.errors:NotNoneError',
'pydantic.errors:NumberNotGeError',
'pydantic.errors:NumberNotGtError',
'pydantic.errors:NumberNotLeError',
'pydantic.errors:NumberNotLtError',
'pydantic.errors:NumberNotMultipleError',
'pydantic.errors:PathError',
'pydantic.errors:PathNotADirectoryError',
'pydantic.errors:PathNotAFileError',
'pydantic.errors:PathNotExistsError',
'pydantic.errors:PatternError',
'pydantic.errors:PyObjectError',
'pydantic.errors:PydanticTypeError',
'pydantic.errors:PydanticValueError',
'pydantic.errors:SequenceError',
'pydantic.errors:SetError',
'pydantic.errors:SetMaxLengthError',
'pydantic.errors:SetMinLengthError',
'pydantic.errors:StrError',
'pydantic.errors:StrRegexError',
'pydantic.errors:StrictBoolError',
'pydantic.errors:SubclassError',
'pydantic.errors:TimeError',
'pydantic.errors:TupleError',
'pydantic.errors:TupleLengthError',
'pydantic.errors:UUIDError',
'pydantic.errors:UUIDVersionError',
'pydantic.errors:UrlError',
'pydantic.errors:UrlExtraError',
'pydantic.errors:UrlHostError',
'pydantic.errors:UrlHostTldError',
'pydantic.errors:UrlPortError',
'pydantic.errors:UrlSchemeError',
'pydantic.errors:UrlSchemePermittedError',
'pydantic.errors:UrlUserInfoError',
'pydantic.errors:WrongConstantError',
'pydantic.main:validate_model',
'pydantic.networks:stricturl',
'pydantic:parse_file_as',
'pydantic:parse_raw_as',
'pydantic:stricturl',
'pydantic.tools:parse_file_as',
'pydantic.tools:parse_raw_as',
'pydantic.types:ConstrainedBytes',
'pydantic.types:ConstrainedDate',
'pydantic.types:ConstrainedDecimal',
'pydantic.types:ConstrainedFloat',
'pydantic.types:ConstrainedFrozenSet',
'pydantic.types:ConstrainedInt',
'pydantic.types:ConstrainedList',
'pydantic.types:ConstrainedSet',
'pydantic.types:ConstrainedStr',
'pydantic.types:JsonWrapper',
'pydantic.types:NoneBytes',
'pydantic.types:NoneStr',
'pydantic.types:NoneStrBytes',
'pydantic.types:StrBytes',
'pydantic.typing:evaluate_forwardref',
'pydantic.typing:AbstractSetIntStr',
'pydantic.typing:AnyCallable',
'pydantic.typing:AnyClassMethod',
'pydantic.typing:CallableGenerator',
'pydantic.typing:DictAny',
'pydantic.typing:DictIntStrAny',
'pydantic.typing:DictStrAny',
'pydantic.typing:IntStr',
'pydantic.typing:ListStr',
'pydantic.typing:MappingIntStrAny',
'pydantic.typing:NoArgAnyCallable',
'pydantic.typing:NoneType',
'pydantic.typing:ReprArgs',
'pydantic.typing:SetStr',
'pydantic.typing:StrPath',
'pydantic.typing:TupleGenerator',
'pydantic.typing:WithArgsTypes',
'pydantic.typing:all_literal_values',
'pydantic.typing:display_as_type',
'pydantic.typing:get_all_type_hints',
'pydantic.typing:get_args',
'pydantic.typing:get_origin',
'pydantic.typing:get_sub_types',
'pydantic.typing:is_callable_type',
'pydantic.typing:is_classvar',
'pydantic.typing:is_finalvar',
'pydantic.typing:is_literal_type',
'pydantic.typing:is_namedtuple',
'pydantic.typing:is_new_type',
'pydantic.typing:is_none_type',
'pydantic.typing:is_typeddict',
'pydantic.typing:is_typeddict_special',
'pydantic.typing:is_union',
'pydantic.typing:new_type_supertype',
'pydantic.typing:resolve_annotations',
'pydantic.typing:typing_base',
'pydantic.typing:update_field_forward_refs',
'pydantic.typing:update_model_forward_refs',
'pydantic.utils:ClassAttribute',
'pydantic.utils:DUNDER_ATTRIBUTES',
'pydantic.utils:PyObjectStr',
'pydantic.utils:ValueItems',
'pydantic.utils:almost_equal_floats',
'pydantic.utils:get_discriminator_alias_and_values',
'pydantic.utils:get_model',
'pydantic.utils:get_unique_discriminator_alias',
'pydantic.utils:in_ipython',
'pydantic.utils:is_valid_identifier',
'pydantic.utils:path_type',
'pydantic.utils:validate_field_name',
'pydantic:validate_model',
}
def getattr_migration(module: str) -> Callable[[str], Any]:
"""Implement PEP 562 for objects that were either moved or removed on the migration
to V2.
Args:
module: The module name.
Returns:
A callable that will raise an error if the object is not found.
"""
# This avoids circular import with errors.py.
from .errors import PydanticImportError
def wrapper(name: str) -> object:
"""Raise an error if the object is not found, or warn if it was moved.
In case it was moved, it still returns the object.
Args:
name: The object name.
Returns:
The object.
"""
if name == '__path__':
raise AttributeError(f'module {module!r} has no attribute {name!r}')
import warnings
from ._internal._validators import import_string
import_path = f'{module}:{name}'
if import_path in MOVED_IN_V2.keys():
new_location = MOVED_IN_V2[import_path]
warnings.warn(
f'`{import_path}` has been moved to `{new_location}`.',
category=PydanticDeprecatedSince20,
stacklevel=2,
)
return import_string(MOVED_IN_V2[import_path])
if import_path in DEPRECATED_MOVED_IN_V2:
# skip the warning here because a deprecation warning will be raised elsewhere
return import_string(DEPRECATED_MOVED_IN_V2[import_path])
if import_path in REDIRECT_TO_V1:
new_location = REDIRECT_TO_V1[import_path]
warnings.warn(
f'`{import_path}` has been removed. We are importing from `{new_location}` instead.'
'See the migration guide for more details: https://docs.pydantic.dev/latest/migration/',
category=PydanticDeprecatedSince20,
stacklevel=2,
)
return import_string(REDIRECT_TO_V1[import_path])
if import_path == 'pydantic:BaseSettings':
raise PydanticImportError(
'`BaseSettings` has been moved to the `pydantic-settings` package. '
f'See https://docs.pydantic.dev/{version_short()}/migration/#basesettings-has-moved-to-pydantic-settings '
'for more details.'
)
if import_path in REMOVED_IN_V2:
raise PydanticImportError(f'`{import_path}` has been removed in V2.')
globals: dict[str, Any] = sys.modules[module].__dict__
if name in globals:
return globals[name]
raise AttributeError(f'module {module!r} has no attribute {name!r}')
return wrapper

View File

@@ -0,0 +1,62 @@
"""Alias generators for converting between different capitalization conventions."""
import re
__all__ = ('to_pascal', 'to_camel', 'to_snake')
# TODO: in V3, change the argument names to be more descriptive
# Generally, don't only convert from snake_case, or name the functions
# more specifically like snake_to_camel.
def to_pascal(snake: str) -> str:
"""Convert a snake_case string to PascalCase.
Args:
snake: The string to convert.
Returns:
The PascalCase string.
"""
camel = snake.title()
return re.sub('([0-9A-Za-z])_(?=[0-9A-Z])', lambda m: m.group(1), camel)
def to_camel(snake: str) -> str:
"""Convert a snake_case string to camelCase.
Args:
snake: The string to convert.
Returns:
The converted camelCase string.
"""
# If the string is already in camelCase and does not contain a digit followed
# by a lowercase letter, return it as it is
if re.match('^[a-z]+[A-Za-z0-9]*$', snake) and not re.search(r'\d[a-z]', snake):
return snake
camel = to_pascal(snake)
return re.sub('(^_*[A-Z])', lambda m: m.group(1).lower(), camel)
def to_snake(camel: str) -> str:
"""Convert a PascalCase, camelCase, or kebab-case string to snake_case.
Args:
camel: The string to convert.
Returns:
The converted string in snake_case.
"""
# Handle the sequence of uppercase letters followed by a lowercase letter
snake = re.sub(r'([A-Z]+)([A-Z][a-z])', lambda m: f'{m.group(1)}_{m.group(2)}', camel)
# Insert an underscore between a lowercase letter and an uppercase letter
snake = re.sub(r'([a-z])([A-Z])', lambda m: f'{m.group(1)}_{m.group(2)}', snake)
# Insert an underscore between a digit and an uppercase letter
snake = re.sub(r'([0-9])([A-Z])', lambda m: f'{m.group(1)}_{m.group(2)}', snake)
# Insert an underscore between a lowercase letter and a digit
snake = re.sub(r'([a-z])([0-9])', lambda m: f'{m.group(1)}_{m.group(2)}', snake)
# Replace hyphens with underscores to handle kebab-case
snake = snake.replace('-', '_')
return snake.lower()

View File

@@ -0,0 +1,135 @@
"""Support for alias configurations."""
from __future__ import annotations
import dataclasses
from typing import Any, Callable, Literal
from pydantic_core import PydanticUndefined
from ._internal import _internal_dataclass
__all__ = ('AliasGenerator', 'AliasPath', 'AliasChoices')
@dataclasses.dataclass(**_internal_dataclass.slots_true)
class AliasPath:
"""!!! abstract "Usage Documentation"
[`AliasPath` and `AliasChoices`](../concepts/alias.md#aliaspath-and-aliaschoices)
A data class used by `validation_alias` as a convenience to create aliases.
Attributes:
path: A list of string or integer aliases.
"""
path: list[int | str]
def __init__(self, first_arg: str, *args: str | int) -> None:
self.path = [first_arg] + list(args)
def convert_to_aliases(self) -> list[str | int]:
"""Converts arguments to a list of string or integer aliases.
Returns:
The list of aliases.
"""
return self.path
def search_dict_for_path(self, d: dict) -> Any:
"""Searches a dictionary for the path specified by the alias.
Returns:
The value at the specified path, or `PydanticUndefined` if the path is not found.
"""
v = d
for k in self.path:
if isinstance(v, str):
# disallow indexing into a str, like for AliasPath('x', 0) and x='abc'
return PydanticUndefined
try:
v = v[k]
except (KeyError, IndexError, TypeError):
return PydanticUndefined
return v
@dataclasses.dataclass(**_internal_dataclass.slots_true)
class AliasChoices:
"""!!! abstract "Usage Documentation"
[`AliasPath` and `AliasChoices`](../concepts/alias.md#aliaspath-and-aliaschoices)
A data class used by `validation_alias` as a convenience to create aliases.
Attributes:
choices: A list containing a string or `AliasPath`.
"""
choices: list[str | AliasPath]
def __init__(self, first_choice: str | AliasPath, *choices: str | AliasPath) -> None:
self.choices = [first_choice] + list(choices)
def convert_to_aliases(self) -> list[list[str | int]]:
"""Converts arguments to a list of lists containing string or integer aliases.
Returns:
The list of aliases.
"""
aliases: list[list[str | int]] = []
for c in self.choices:
if isinstance(c, AliasPath):
aliases.append(c.convert_to_aliases())
else:
aliases.append([c])
return aliases
@dataclasses.dataclass(**_internal_dataclass.slots_true)
class AliasGenerator:
"""!!! abstract "Usage Documentation"
[Using an `AliasGenerator`](../concepts/alias.md#using-an-aliasgenerator)
A data class used by `alias_generator` as a convenience to create various aliases.
Attributes:
alias: A callable that takes a field name and returns an alias for it.
validation_alias: A callable that takes a field name and returns a validation alias for it.
serialization_alias: A callable that takes a field name and returns a serialization alias for it.
"""
alias: Callable[[str], str] | None = None
validation_alias: Callable[[str], str | AliasPath | AliasChoices] | None = None
serialization_alias: Callable[[str], str] | None = None
def _generate_alias(
self,
alias_kind: Literal['alias', 'validation_alias', 'serialization_alias'],
allowed_types: tuple[type[str] | type[AliasPath] | type[AliasChoices], ...],
field_name: str,
) -> str | AliasPath | AliasChoices | None:
"""Generate an alias of the specified kind. Returns None if the alias generator is None.
Raises:
TypeError: If the alias generator produces an invalid type.
"""
alias = None
if alias_generator := getattr(self, alias_kind):
alias = alias_generator(field_name)
if alias and not isinstance(alias, allowed_types):
raise TypeError(
f'Invalid `{alias_kind}` type. `{alias_kind}` generator must produce one of `{allowed_types}`'
)
return alias
def generate_aliases(self, field_name: str) -> tuple[str | None, str | AliasPath | AliasChoices | None, str | None]:
"""Generate `alias`, `validation_alias`, and `serialization_alias` for a field.
Returns:
A tuple of three aliases - validation, alias, and serialization.
"""
alias = self._generate_alias('alias', (str,), field_name)
validation_alias = self._generate_alias('validation_alias', (str, AliasChoices, AliasPath), field_name)
serialization_alias = self._generate_alias('serialization_alias', (str,), field_name)
return alias, validation_alias, serialization_alias # type: ignore

View File

@@ -0,0 +1,122 @@
"""Type annotations to use with `__get_pydantic_core_schema__` and `__get_pydantic_json_schema__`."""
from __future__ import annotations as _annotations
from typing import TYPE_CHECKING, Any, Union
from pydantic_core import core_schema
if TYPE_CHECKING:
from ._internal._namespace_utils import NamespacesTuple
from .json_schema import JsonSchemaMode, JsonSchemaValue
CoreSchemaOrField = Union[
core_schema.CoreSchema,
core_schema.ModelField,
core_schema.DataclassField,
core_schema.TypedDictField,
core_schema.ComputedField,
]
__all__ = 'GetJsonSchemaHandler', 'GetCoreSchemaHandler'
class GetJsonSchemaHandler:
"""Handler to call into the next JSON schema generation function.
Attributes:
mode: Json schema mode, can be `validation` or `serialization`.
"""
mode: JsonSchemaMode
def __call__(self, core_schema: CoreSchemaOrField, /) -> JsonSchemaValue:
"""Call the inner handler and get the JsonSchemaValue it returns.
This will call the next JSON schema modifying function up until it calls
into `pydantic.json_schema.GenerateJsonSchema`, which will raise a
`pydantic.errors.PydanticInvalidForJsonSchema` error if it cannot generate
a JSON schema.
Args:
core_schema: A `pydantic_core.core_schema.CoreSchema`.
Returns:
JsonSchemaValue: The JSON schema generated by the inner JSON schema modify
functions.
"""
raise NotImplementedError
def resolve_ref_schema(self, maybe_ref_json_schema: JsonSchemaValue, /) -> JsonSchemaValue:
"""Get the real schema for a `{"$ref": ...}` schema.
If the schema given is not a `$ref` schema, it will be returned as is.
This means you don't have to check before calling this function.
Args:
maybe_ref_json_schema: A JsonSchemaValue which may be a `$ref` schema.
Raises:
LookupError: If the ref is not found.
Returns:
JsonSchemaValue: A JsonSchemaValue that has no `$ref`.
"""
raise NotImplementedError
class GetCoreSchemaHandler:
"""Handler to call into the next CoreSchema schema generation function."""
def __call__(self, source_type: Any, /) -> core_schema.CoreSchema:
"""Call the inner handler and get the CoreSchema it returns.
This will call the next CoreSchema modifying function up until it calls
into Pydantic's internal schema generation machinery, which will raise a
`pydantic.errors.PydanticSchemaGenerationError` error if it cannot generate
a CoreSchema for the given source type.
Args:
source_type: The input type.
Returns:
CoreSchema: The `pydantic-core` CoreSchema generated.
"""
raise NotImplementedError
def generate_schema(self, source_type: Any, /) -> core_schema.CoreSchema:
"""Generate a schema unrelated to the current context.
Use this function if e.g. you are handling schema generation for a sequence
and want to generate a schema for its items.
Otherwise, you may end up doing something like applying a `min_length` constraint
that was intended for the sequence itself to its items!
Args:
source_type: The input type.
Returns:
CoreSchema: The `pydantic-core` CoreSchema generated.
"""
raise NotImplementedError
def resolve_ref_schema(self, maybe_ref_schema: core_schema.CoreSchema, /) -> core_schema.CoreSchema:
"""Get the real schema for a `definition-ref` schema.
If the schema given is not a `definition-ref` schema, it will be returned as is.
This means you don't have to check before calling this function.
Args:
maybe_ref_schema: A `CoreSchema`, `ref`-based or not.
Raises:
LookupError: If the `ref` is not found.
Returns:
A concrete `CoreSchema`.
"""
raise NotImplementedError
@property
def field_name(self) -> str | None:
"""Get the name of the closest field to this validator."""
raise NotImplementedError
def _get_types_namespace(self) -> NamespacesTuple:
"""Internal method used during type resolution for serializer annotations."""
raise NotImplementedError