updates
This commit is contained in:
@@ -1,24 +1,27 @@
|
||||
# flake8: noqa
|
||||
from . import dataclasses
|
||||
from .annotated_types import create_model_from_namedtuple, create_model_from_typeddict
|
||||
from .class_validators import root_validator, validator
|
||||
from .config import BaseConfig, ConfigDict, Extra
|
||||
from .decorator import validate_arguments
|
||||
from .env_settings import BaseSettings
|
||||
from .error_wrappers import ValidationError
|
||||
from .errors import *
|
||||
from .fields import Field, PrivateAttr, Required
|
||||
from .main import *
|
||||
from .networks import *
|
||||
from .parse import Protocol
|
||||
from .tools import *
|
||||
from .types import *
|
||||
from .version import VERSION, compiled
|
||||
import sys
|
||||
import warnings
|
||||
|
||||
from pydantic.v1 import dataclasses
|
||||
from pydantic.v1.annotated_types import create_model_from_namedtuple, create_model_from_typeddict
|
||||
from pydantic.v1.class_validators import root_validator, validator
|
||||
from pydantic.v1.config import BaseConfig, ConfigDict, Extra
|
||||
from pydantic.v1.decorator import validate_arguments
|
||||
from pydantic.v1.env_settings import BaseSettings
|
||||
from pydantic.v1.error_wrappers import ValidationError
|
||||
from pydantic.v1.errors import *
|
||||
from pydantic.v1.fields import Field, PrivateAttr, Required
|
||||
from pydantic.v1.main import *
|
||||
from pydantic.v1.networks import *
|
||||
from pydantic.v1.parse import Protocol
|
||||
from pydantic.v1.tools import *
|
||||
from pydantic.v1.types import *
|
||||
from pydantic.v1.version import VERSION, compiled
|
||||
|
||||
__version__ = VERSION
|
||||
|
||||
# WARNING __all__ from .errors is not included here, it will be removed as an export here in v2
|
||||
# please use "from pydantic.errors import ..." instead
|
||||
# WARNING __all__ from pydantic.errors is not included here, it will be removed as an export here in v2
|
||||
# please use "from pydantic.v1.errors import ..." instead
|
||||
__all__ = [
|
||||
# annotated types utils
|
||||
'create_model_from_namedtuple',
|
||||
@@ -129,3 +132,11 @@ __all__ = [
|
||||
'compiled',
|
||||
'VERSION',
|
||||
]
|
||||
|
||||
|
||||
if sys.version_info >= (3, 14):
|
||||
warnings.warn(
|
||||
"Core Pydantic V1 functionality isn't compatible with Python 3.14 or greater.",
|
||||
UserWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -35,7 +35,7 @@ import hypothesis.strategies as st
|
||||
import pydantic
|
||||
import pydantic.color
|
||||
import pydantic.types
|
||||
from pydantic.utils import lenient_issubclass
|
||||
from pydantic.v1.utils import lenient_issubclass
|
||||
|
||||
# FilePath and DirectoryPath are explicitly unsupported, as we'd have to create
|
||||
# them on-disk, and that's unsafe in general without being told *where* to do so.
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import sys
|
||||
from typing import TYPE_CHECKING, Any, Dict, FrozenSet, NamedTuple, Type
|
||||
|
||||
from .fields import Required
|
||||
from .main import BaseModel, create_model
|
||||
from .typing import is_typeddict, is_typeddict_special
|
||||
from pydantic.v1.fields import Required
|
||||
from pydantic.v1.main import BaseModel, create_model
|
||||
from pydantic.v1.typing import is_typeddict, is_typeddict_special
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
@@ -5,12 +5,12 @@ from itertools import chain
|
||||
from types import FunctionType
|
||||
from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, Type, Union, overload
|
||||
|
||||
from .errors import ConfigError
|
||||
from .typing import AnyCallable
|
||||
from .utils import ROOT_KEY, in_ipython
|
||||
from pydantic.v1.errors import ConfigError
|
||||
from pydantic.v1.typing import AnyCallable
|
||||
from pydantic.v1.utils import ROOT_KEY, in_ipython
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .typing import AnyClassMethod
|
||||
from pydantic.v1.typing import AnyClassMethod
|
||||
|
||||
|
||||
class Validator:
|
||||
@@ -36,9 +36,9 @@ class Validator:
|
||||
if TYPE_CHECKING:
|
||||
from inspect import Signature
|
||||
|
||||
from .config import BaseConfig
|
||||
from .fields import ModelField
|
||||
from .types import ModelOrDc
|
||||
from pydantic.v1.config import BaseConfig
|
||||
from pydantic.v1.fields import ModelField
|
||||
from pydantic.v1.types import ModelOrDc
|
||||
|
||||
ValidatorCallable = Callable[[Optional[ModelOrDc], Any, Dict[str, Any], ModelField, Type[BaseConfig]], Any]
|
||||
ValidatorsList = List[ValidatorCallable]
|
||||
|
||||
@@ -12,11 +12,11 @@ import re
|
||||
from colorsys import hls_to_rgb, rgb_to_hls
|
||||
from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union, cast
|
||||
|
||||
from .errors import ColorError
|
||||
from .utils import Representation, almost_equal_floats
|
||||
from pydantic.v1.errors import ColorError
|
||||
from pydantic.v1.utils import Representation, almost_equal_floats
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .typing import CallableGenerator, ReprArgs
|
||||
from pydantic.v1.typing import CallableGenerator, ReprArgs
|
||||
|
||||
ColorTuple = Union[Tuple[int, int, int], Tuple[int, int, int, float]]
|
||||
ColorType = Union[ColorTuple, str]
|
||||
|
||||
@@ -4,15 +4,15 @@ from typing import TYPE_CHECKING, Any, Callable, Dict, ForwardRef, Optional, Tup
|
||||
|
||||
from typing_extensions import Literal, Protocol
|
||||
|
||||
from .typing import AnyArgTCallable, AnyCallable
|
||||
from .utils import GetterDict
|
||||
from .version import compiled
|
||||
from pydantic.v1.typing import AnyArgTCallable, AnyCallable
|
||||
from pydantic.v1.utils import GetterDict
|
||||
from pydantic.v1.version import compiled
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing import overload
|
||||
|
||||
from .fields import ModelField
|
||||
from .main import BaseModel
|
||||
from pydantic.v1.fields import ModelField
|
||||
from pydantic.v1.main import BaseModel
|
||||
|
||||
ConfigType = Type['BaseConfig']
|
||||
|
||||
|
||||
@@ -36,21 +36,28 @@ import dataclasses
|
||||
import sys
|
||||
from contextlib import contextmanager
|
||||
from functools import wraps
|
||||
|
||||
try:
|
||||
from functools import cached_property
|
||||
except ImportError:
|
||||
# cached_property available only for python3.8+
|
||||
pass
|
||||
|
||||
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, Generator, Optional, Type, TypeVar, Union, overload
|
||||
|
||||
from typing_extensions import dataclass_transform
|
||||
|
||||
from .class_validators import gather_all_validators
|
||||
from .config import BaseConfig, ConfigDict, Extra, get_config
|
||||
from .error_wrappers import ValidationError
|
||||
from .errors import DataclassTypeError
|
||||
from .fields import Field, FieldInfo, Required, Undefined
|
||||
from .main import create_model, validate_model
|
||||
from .utils import ClassAttribute
|
||||
from pydantic.v1.class_validators import gather_all_validators
|
||||
from pydantic.v1.config import BaseConfig, ConfigDict, Extra, get_config
|
||||
from pydantic.v1.error_wrappers import ValidationError
|
||||
from pydantic.v1.errors import DataclassTypeError
|
||||
from pydantic.v1.fields import Field, FieldInfo, Required, Undefined
|
||||
from pydantic.v1.main import create_model, validate_model
|
||||
from pydantic.v1.utils import ClassAttribute
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .main import BaseModel
|
||||
from .typing import CallableGenerator, NoArgAnyCallable
|
||||
from pydantic.v1.main import BaseModel
|
||||
from pydantic.v1.typing import CallableGenerator, NoArgAnyCallable
|
||||
|
||||
DataclassT = TypeVar('DataclassT', bound='Dataclass')
|
||||
|
||||
@@ -409,6 +416,17 @@ def create_pydantic_model_from_dataclass(
|
||||
return model
|
||||
|
||||
|
||||
if sys.version_info >= (3, 8):
|
||||
|
||||
def _is_field_cached_property(obj: 'Dataclass', k: str) -> bool:
|
||||
return isinstance(getattr(type(obj), k, None), cached_property)
|
||||
|
||||
else:
|
||||
|
||||
def _is_field_cached_property(obj: 'Dataclass', k: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _dataclass_validate_values(self: 'Dataclass') -> None:
|
||||
# validation errors can occur if this function is called twice on an already initialised dataclass.
|
||||
# for example if Extra.forbid is enabled, it would consider __pydantic_initialised__ an invalid extra property
|
||||
@@ -417,9 +435,13 @@ def _dataclass_validate_values(self: 'Dataclass') -> None:
|
||||
if getattr(self, '__pydantic_has_field_info_default__', False):
|
||||
# We need to remove `FieldInfo` values since they are not valid as input
|
||||
# It's ok to do that because they are obviously the default values!
|
||||
input_data = {k: v for k, v in self.__dict__.items() if not isinstance(v, FieldInfo)}
|
||||
input_data = {
|
||||
k: v
|
||||
for k, v in self.__dict__.items()
|
||||
if not (isinstance(v, FieldInfo) or _is_field_cached_property(self, k))
|
||||
}
|
||||
else:
|
||||
input_data = self.__dict__
|
||||
input_data = {k: v for k, v in self.__dict__.items() if not _is_field_cached_property(self, k)}
|
||||
d, _, validation_error = validate_model(self.__pydantic_model__, input_data, cls=self.__class__)
|
||||
if validation_error:
|
||||
raise validation_error
|
||||
|
||||
@@ -18,7 +18,7 @@ import re
|
||||
from datetime import date, datetime, time, timedelta, timezone
|
||||
from typing import Dict, Optional, Type, Union
|
||||
|
||||
from . import errors
|
||||
from pydantic.v1 import errors
|
||||
|
||||
date_expr = r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})'
|
||||
time_expr = (
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
from functools import wraps
|
||||
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional, Tuple, Type, TypeVar, Union, overload
|
||||
|
||||
from . import validator
|
||||
from .config import Extra
|
||||
from .errors import ConfigError
|
||||
from .main import BaseModel, create_model
|
||||
from .typing import get_all_type_hints
|
||||
from .utils import to_camel
|
||||
from pydantic.v1 import validator
|
||||
from pydantic.v1.config import Extra
|
||||
from pydantic.v1.errors import ConfigError
|
||||
from pydantic.v1.main import BaseModel, create_model
|
||||
from pydantic.v1.typing import get_all_type_hints
|
||||
from pydantic.v1.utils import to_camel
|
||||
|
||||
__all__ = ('validate_arguments',)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .typing import AnyCallable
|
||||
from pydantic.v1.typing import AnyCallable
|
||||
|
||||
AnyCallableT = TypeVar('AnyCallableT', bound=AnyCallable)
|
||||
ConfigType = Union[None, Type[Any], Dict[str, Any]]
|
||||
|
||||
@@ -3,12 +3,12 @@ import warnings
|
||||
from pathlib import Path
|
||||
from typing import AbstractSet, Any, Callable, ClassVar, Dict, List, Mapping, Optional, Tuple, Type, Union
|
||||
|
||||
from .config import BaseConfig, Extra
|
||||
from .fields import ModelField
|
||||
from .main import BaseModel
|
||||
from .types import JsonWrapper
|
||||
from .typing import StrPath, display_as_type, get_origin, is_union
|
||||
from .utils import deep_update, lenient_issubclass, path_type, sequence_like
|
||||
from pydantic.v1.config import BaseConfig, Extra
|
||||
from pydantic.v1.fields import ModelField
|
||||
from pydantic.v1.main import BaseModel
|
||||
from pydantic.v1.types import JsonWrapper
|
||||
from pydantic.v1.typing import StrPath, display_as_type, get_origin, is_union
|
||||
from pydantic.v1.utils import deep_update, lenient_issubclass, path_type, sequence_like
|
||||
|
||||
env_file_sentinel = str(object())
|
||||
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import json
|
||||
from typing import TYPE_CHECKING, Any, Dict, Generator, List, Optional, Sequence, Tuple, Type, Union
|
||||
|
||||
from .json import pydantic_encoder
|
||||
from .utils import Representation
|
||||
from pydantic.v1.json import pydantic_encoder
|
||||
from pydantic.v1.utils import Representation
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
from .config import BaseConfig
|
||||
from .types import ModelOrDc
|
||||
from .typing import ReprArgs
|
||||
from pydantic.v1.config import BaseConfig
|
||||
from pydantic.v1.types import ModelOrDc
|
||||
from pydantic.v1.typing import ReprArgs
|
||||
|
||||
Loc = Tuple[Union[int, str], ...]
|
||||
|
||||
@@ -101,7 +101,6 @@ def flatten_errors(
|
||||
) -> Generator['ErrorDict', None, None]:
|
||||
for error in errors:
|
||||
if isinstance(error, ErrorWrapper):
|
||||
|
||||
if loc:
|
||||
error_loc = loc + error.loc_tuple()
|
||||
else:
|
||||
|
||||
@@ -2,12 +2,12 @@ from decimal import Decimal
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Callable, Sequence, Set, Tuple, Type, Union
|
||||
|
||||
from .typing import display_as_type
|
||||
from pydantic.v1.typing import display_as_type
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .typing import DictStrAny
|
||||
from pydantic.v1.typing import DictStrAny
|
||||
|
||||
# explicitly state exports to avoid "from .errors import *" also importing Decimal, Path etc.
|
||||
# explicitly state exports to avoid "from pydantic.v1.errors import *" also importing Decimal, Path etc.
|
||||
__all__ = (
|
||||
'PydanticTypeError',
|
||||
'PydanticValueError',
|
||||
|
||||
@@ -28,12 +28,12 @@ from typing import (
|
||||
|
||||
from typing_extensions import Annotated, Final
|
||||
|
||||
from . import errors as errors_
|
||||
from .class_validators import Validator, make_generic_validator, prep_validators
|
||||
from .error_wrappers import ErrorWrapper
|
||||
from .errors import ConfigError, InvalidDiscriminator, MissingDiscriminator, NoneIsNotAllowedError
|
||||
from .types import Json, JsonWrapper
|
||||
from .typing import (
|
||||
from pydantic.v1 import errors as errors_
|
||||
from pydantic.v1.class_validators import Validator, make_generic_validator, prep_validators
|
||||
from pydantic.v1.error_wrappers import ErrorWrapper
|
||||
from pydantic.v1.errors import ConfigError, InvalidDiscriminator, MissingDiscriminator, NoneIsNotAllowedError
|
||||
from pydantic.v1.types import Json, JsonWrapper
|
||||
from pydantic.v1.typing import (
|
||||
NoArgAnyCallable,
|
||||
convert_generics,
|
||||
display_as_type,
|
||||
@@ -48,7 +48,7 @@ from .typing import (
|
||||
is_union,
|
||||
new_type_supertype,
|
||||
)
|
||||
from .utils import (
|
||||
from pydantic.v1.utils import (
|
||||
PyObjectStr,
|
||||
Representation,
|
||||
ValueItems,
|
||||
@@ -59,7 +59,7 @@ from .utils import (
|
||||
sequence_like,
|
||||
smart_deepcopy,
|
||||
)
|
||||
from .validators import constant_validator, dict_validator, find_validators, validate_json
|
||||
from pydantic.v1.validators import constant_validator, dict_validator, find_validators, validate_json
|
||||
|
||||
Required: Any = Ellipsis
|
||||
|
||||
@@ -83,11 +83,11 @@ class UndefinedType:
|
||||
Undefined = UndefinedType()
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .class_validators import ValidatorsList
|
||||
from .config import BaseConfig
|
||||
from .error_wrappers import ErrorList
|
||||
from .types import ModelOrDc
|
||||
from .typing import AbstractSetIntStr, MappingIntStrAny, ReprArgs
|
||||
from pydantic.v1.class_validators import ValidatorsList
|
||||
from pydantic.v1.config import BaseConfig
|
||||
from pydantic.v1.error_wrappers import ErrorList
|
||||
from pydantic.v1.types import ModelOrDc
|
||||
from pydantic.v1.typing import AbstractSetIntStr, MappingIntStrAny, ReprArgs
|
||||
|
||||
ValidateReturn = Tuple[Optional[Any], Optional[ErrorList]]
|
||||
LocStr = Union[Tuple[Union[int, str], ...], str]
|
||||
@@ -178,7 +178,6 @@ class FieldInfo(Representation):
|
||||
self.extra = kwargs
|
||||
|
||||
def __repr_args__(self) -> 'ReprArgs':
|
||||
|
||||
field_defaults_to_hide: Dict[str, Any] = {
|
||||
'repr': True,
|
||||
**self.__field_constraints__,
|
||||
@@ -405,7 +404,6 @@ class ModelField(Representation):
|
||||
alias: Optional[str] = None,
|
||||
field_info: Optional[FieldInfo] = None,
|
||||
) -> None:
|
||||
|
||||
self.name: str = name
|
||||
self.has_alias: bool = alias is not None
|
||||
self.alias: str = alias if alias is not None else name
|
||||
@@ -492,7 +490,7 @@ class ModelField(Representation):
|
||||
class_validators: Optional[Dict[str, Validator]],
|
||||
config: Type['BaseConfig'],
|
||||
) -> 'ModelField':
|
||||
from .schema import get_annotation_from_field_info
|
||||
from pydantic.v1.schema import get_annotation_from_field_info
|
||||
|
||||
field_info, value = cls._get_field_info(name, annotation, value, config)
|
||||
required: 'BoolUndefined' = Undefined
|
||||
@@ -852,7 +850,6 @@ class ModelField(Representation):
|
||||
def validate(
|
||||
self, v: Any, values: Dict[str, Any], *, loc: 'LocStr', cls: Optional['ModelOrDc'] = None
|
||||
) -> 'ValidateReturn':
|
||||
|
||||
assert self.type_.__class__ is not DeferredType
|
||||
|
||||
if self.type_.__class__ is ForwardRef:
|
||||
@@ -1163,7 +1160,7 @@ class ModelField(Representation):
|
||||
"""
|
||||
Whether the field is "complex" eg. env variables should be parsed as JSON.
|
||||
"""
|
||||
from .main import BaseModel
|
||||
from pydantic.v1.main import BaseModel
|
||||
|
||||
return (
|
||||
self.shape != SHAPE_SINGLETON
|
||||
|
||||
@@ -22,12 +22,12 @@ from weakref import WeakKeyDictionary, WeakValueDictionary
|
||||
|
||||
from typing_extensions import Annotated, Literal as ExtLiteral
|
||||
|
||||
from .class_validators import gather_all_validators
|
||||
from .fields import DeferredType
|
||||
from .main import BaseModel, create_model
|
||||
from .types import JsonWrapper
|
||||
from .typing import display_as_type, get_all_type_hints, get_args, get_origin, typing_base
|
||||
from .utils import all_identical, lenient_issubclass
|
||||
from pydantic.v1.class_validators import gather_all_validators
|
||||
from pydantic.v1.fields import DeferredType
|
||||
from pydantic.v1.main import BaseModel, create_model
|
||||
from pydantic.v1.types import JsonWrapper
|
||||
from pydantic.v1.typing import display_as_type, get_all_type_hints, get_args, get_origin, typing_base
|
||||
from pydantic.v1.utils import all_identical, lenient_issubclass
|
||||
|
||||
if sys.version_info >= (3, 10):
|
||||
from typing import _UnionGenericAlias
|
||||
|
||||
@@ -9,9 +9,9 @@ from types import GeneratorType
|
||||
from typing import Any, Callable, Dict, Type, Union
|
||||
from uuid import UUID
|
||||
|
||||
from .color import Color
|
||||
from .networks import NameEmail
|
||||
from .types import SecretBytes, SecretStr
|
||||
from pydantic.v1.color import Color
|
||||
from pydantic.v1.networks import NameEmail
|
||||
from pydantic.v1.types import SecretBytes, SecretStr
|
||||
|
||||
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
|
||||
|
||||
@@ -72,7 +72,7 @@ ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
|
||||
def pydantic_encoder(obj: Any) -> Any:
|
||||
from dataclasses import asdict, is_dataclass
|
||||
|
||||
from .main import BaseModel
|
||||
from pydantic.v1.main import BaseModel
|
||||
|
||||
if isinstance(obj, BaseModel):
|
||||
return obj.dict()
|
||||
|
||||
@@ -26,11 +26,11 @@ from typing import (
|
||||
|
||||
from typing_extensions import dataclass_transform
|
||||
|
||||
from .class_validators import ValidatorGroup, extract_root_validators, extract_validators, inherit_validators
|
||||
from .config import BaseConfig, Extra, inherit_config, prepare_config
|
||||
from .error_wrappers import ErrorWrapper, ValidationError
|
||||
from .errors import ConfigError, DictError, ExtraError, MissingError
|
||||
from .fields import (
|
||||
from pydantic.v1.class_validators import ValidatorGroup, extract_root_validators, extract_validators, inherit_validators
|
||||
from pydantic.v1.config import BaseConfig, Extra, inherit_config, prepare_config
|
||||
from pydantic.v1.error_wrappers import ErrorWrapper, ValidationError
|
||||
from pydantic.v1.errors import ConfigError, DictError, ExtraError, MissingError
|
||||
from pydantic.v1.fields import (
|
||||
MAPPING_LIKE_SHAPES,
|
||||
Field,
|
||||
ModelField,
|
||||
@@ -39,11 +39,11 @@ from .fields import (
|
||||
Undefined,
|
||||
is_finalvar_with_default_val,
|
||||
)
|
||||
from .json import custom_pydantic_encoder, pydantic_encoder
|
||||
from .parse import Protocol, load_file, load_str_bytes
|
||||
from .schema import default_ref_template, model_schema
|
||||
from .types import PyObject, StrBytes
|
||||
from .typing import (
|
||||
from pydantic.v1.json import custom_pydantic_encoder, pydantic_encoder
|
||||
from pydantic.v1.parse import Protocol, load_file, load_str_bytes
|
||||
from pydantic.v1.schema import default_ref_template, model_schema
|
||||
from pydantic.v1.types import PyObject, StrBytes
|
||||
from pydantic.v1.typing import (
|
||||
AnyCallable,
|
||||
get_args,
|
||||
get_origin,
|
||||
@@ -53,7 +53,7 @@ from .typing import (
|
||||
resolve_annotations,
|
||||
update_model_forward_refs,
|
||||
)
|
||||
from .utils import (
|
||||
from pydantic.v1.utils import (
|
||||
DUNDER_ATTRIBUTES,
|
||||
ROOT_KEY,
|
||||
ClassAttribute,
|
||||
@@ -73,9 +73,9 @@ from .utils import (
|
||||
if TYPE_CHECKING:
|
||||
from inspect import Signature
|
||||
|
||||
from .class_validators import ValidatorListDict
|
||||
from .types import ModelOrDc
|
||||
from .typing import (
|
||||
from pydantic.v1.class_validators import ValidatorListDict
|
||||
from pydantic.v1.types import ModelOrDc
|
||||
from pydantic.v1.typing import (
|
||||
AbstractSetIntStr,
|
||||
AnyClassMethod,
|
||||
CallableGenerator,
|
||||
@@ -282,6 +282,12 @@ class ModelMetaclass(ABCMeta):
|
||||
cls = super().__new__(mcs, name, bases, new_namespace, **kwargs)
|
||||
# set __signature__ attr only for model class, but not for its instances
|
||||
cls.__signature__ = ClassAttribute('__signature__', generate_model_signature(cls.__init__, fields, config))
|
||||
|
||||
if not _is_base_model_class_defined:
|
||||
# Cython does not understand the `if TYPE_CHECKING:` condition in the
|
||||
# BaseModel's body (where annotations are set), so clear them manually:
|
||||
getattr(cls, '__annotations__', {}).clear()
|
||||
|
||||
if resolve_forward_refs:
|
||||
cls.__try_update_forward_refs__()
|
||||
|
||||
@@ -301,7 +307,7 @@ class ModelMetaclass(ABCMeta):
|
||||
|
||||
See #3829 and python/cpython#92810
|
||||
"""
|
||||
return hasattr(instance, '__fields__') and super().__instancecheck__(instance)
|
||||
return hasattr(instance, '__post_root_validators__') and super().__instancecheck__(instance)
|
||||
|
||||
|
||||
object_setattr = object.__setattr__
|
||||
@@ -669,7 +675,7 @@ class BaseModel(Representation, metaclass=ModelMetaclass):
|
||||
def schema_json(
|
||||
cls, *, by_alias: bool = True, ref_template: str = default_ref_template, **dumps_kwargs: Any
|
||||
) -> str:
|
||||
from .json import pydantic_encoder
|
||||
from pydantic.v1.json import pydantic_encoder
|
||||
|
||||
return cls.__config__.json_dumps(
|
||||
cls.schema(by_alias=by_alias, ref_template=ref_template), default=pydantic_encoder, **dumps_kwargs
|
||||
@@ -737,7 +743,6 @@ class BaseModel(Representation, metaclass=ModelMetaclass):
|
||||
exclude_defaults: bool,
|
||||
exclude_none: bool,
|
||||
) -> Any:
|
||||
|
||||
if isinstance(v, BaseModel):
|
||||
if to_dict:
|
||||
v_dict = v.dict(
|
||||
@@ -830,7 +835,6 @@ class BaseModel(Representation, metaclass=ModelMetaclass):
|
||||
exclude_defaults: bool = False,
|
||||
exclude_none: bool = False,
|
||||
) -> 'TupleGenerator':
|
||||
|
||||
# Merge field set excludes with explicit exclude parameter with explicit overriding field set options.
|
||||
# The extra "is not None" guards are not logically necessary but optimizes performance for the simple case.
|
||||
if exclude is not None or self.__exclude_fields__ is not None:
|
||||
|
||||
@@ -57,6 +57,7 @@ from mypy.types import (
|
||||
Type,
|
||||
TypeOfAny,
|
||||
TypeType,
|
||||
TypeVarId,
|
||||
TypeVarType,
|
||||
UnionType,
|
||||
get_proper_type,
|
||||
@@ -65,7 +66,7 @@ from mypy.typevars import fill_typevars
|
||||
from mypy.util import get_unique_redefinition_name
|
||||
from mypy.version import __version__ as mypy_version
|
||||
|
||||
from pydantic.utils import is_valid_field
|
||||
from pydantic.v1.utils import is_valid_field
|
||||
|
||||
try:
|
||||
from mypy.types import TypeVarDef # type: ignore[attr-defined]
|
||||
@@ -208,14 +209,14 @@ class PydanticPlugin(Plugin):
|
||||
default_factory_type = default_factory_type.items()[0] # type: ignore[operator]
|
||||
|
||||
if isinstance(default_factory_type, CallableType):
|
||||
ret_type = default_factory_type.ret_type
|
||||
# mypy doesn't think `ret_type` has `args`, you'd think mypy should know,
|
||||
# add this check in case it varies by version
|
||||
args = getattr(ret_type, 'args', None)
|
||||
if args:
|
||||
if all(isinstance(arg, TypeVarType) for arg in args):
|
||||
# Looks like the default factory is a type like `list` or `dict`, replace all args with `Any`
|
||||
ret_type.args = tuple(default_any_type for _ in args) # type: ignore[attr-defined]
|
||||
ret_type = get_proper_type(default_factory_type.ret_type)
|
||||
if (
|
||||
isinstance(ret_type, Instance)
|
||||
and ret_type.args
|
||||
and all(isinstance(arg, TypeVarType) for arg in ret_type.args)
|
||||
):
|
||||
# Looks like the default factory is a type like `list` or `dict`, replace all args with `Any`
|
||||
ret_type = ret_type.copy_modified(args=[default_any_type] * len(ret_type.args))
|
||||
return ret_type
|
||||
|
||||
return default_any_type
|
||||
@@ -498,7 +499,11 @@ class PydanticModelTransformer:
|
||||
tvd = TypeVarType(
|
||||
self_tvar_name,
|
||||
tvar_fullname,
|
||||
-1,
|
||||
(
|
||||
TypeVarId(-1, namespace=ctx.cls.fullname + '.construct')
|
||||
if MYPY_VERSION_TUPLE >= (1, 11)
|
||||
else TypeVarId(-1)
|
||||
),
|
||||
[],
|
||||
obj_type,
|
||||
AnyType(TypeOfAny.from_omitted_generics), # type: ignore[arg-type]
|
||||
@@ -858,9 +863,9 @@ def add_method(
|
||||
arg_kinds.append(arg.kind)
|
||||
|
||||
function_type = ctx.api.named_type(f'{BUILTINS_NAME}.function')
|
||||
signature = CallableType(arg_types, arg_kinds, arg_names, return_type, function_type)
|
||||
if tvar_def:
|
||||
signature.variables = [tvar_def]
|
||||
signature = CallableType(
|
||||
arg_types, arg_kinds, arg_names, return_type, function_type, variables=[tvar_def] if tvar_def else None
|
||||
)
|
||||
|
||||
func = FuncDef(name, args, Block([PassStmt()]))
|
||||
func.info = info
|
||||
|
||||
@@ -27,17 +27,17 @@ from typing import (
|
||||
no_type_check,
|
||||
)
|
||||
|
||||
from . import errors
|
||||
from .utils import Representation, update_not_none
|
||||
from .validators import constr_length_validator, str_validator
|
||||
from pydantic.v1 import errors
|
||||
from pydantic.v1.utils import Representation, update_not_none
|
||||
from pydantic.v1.validators import constr_length_validator, str_validator
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import email_validator
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
from .config import BaseConfig
|
||||
from .fields import ModelField
|
||||
from .typing import AnyCallable
|
||||
from pydantic.v1.config import BaseConfig
|
||||
from pydantic.v1.fields import ModelField
|
||||
from pydantic.v1.typing import AnyCallable
|
||||
|
||||
CallableGenerator = Generator[AnyCallable, None, None]
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Union
|
||||
|
||||
from .types import StrBytes
|
||||
from pydantic.v1.types import StrBytes
|
||||
|
||||
|
||||
class Protocol(str, Enum):
|
||||
|
||||
@@ -31,7 +31,7 @@ from uuid import UUID
|
||||
|
||||
from typing_extensions import Annotated, Literal
|
||||
|
||||
from .fields import (
|
||||
from pydantic.v1.fields import (
|
||||
MAPPING_LIKE_SHAPES,
|
||||
SHAPE_DEQUE,
|
||||
SHAPE_FROZENSET,
|
||||
@@ -46,9 +46,9 @@ from .fields import (
|
||||
FieldInfo,
|
||||
ModelField,
|
||||
)
|
||||
from .json import pydantic_encoder
|
||||
from .networks import AnyUrl, EmailStr
|
||||
from .types import (
|
||||
from pydantic.v1.json import pydantic_encoder
|
||||
from pydantic.v1.networks import AnyUrl, EmailStr
|
||||
from pydantic.v1.types import (
|
||||
ConstrainedDecimal,
|
||||
ConstrainedFloat,
|
||||
ConstrainedFrozenSet,
|
||||
@@ -69,7 +69,7 @@ from .types import (
|
||||
conset,
|
||||
constr,
|
||||
)
|
||||
from .typing import (
|
||||
from pydantic.v1.typing import (
|
||||
all_literal_values,
|
||||
get_args,
|
||||
get_origin,
|
||||
@@ -80,11 +80,11 @@ from .typing import (
|
||||
is_none_type,
|
||||
is_union,
|
||||
)
|
||||
from .utils import ROOT_KEY, get_model, lenient_issubclass
|
||||
from pydantic.v1.utils import ROOT_KEY, get_model, lenient_issubclass
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .dataclasses import Dataclass
|
||||
from .main import BaseModel
|
||||
from pydantic.v1.dataclasses import Dataclass
|
||||
from pydantic.v1.main import BaseModel
|
||||
|
||||
default_prefix = '#/definitions/'
|
||||
default_ref_template = '#/definitions/{model}'
|
||||
@@ -198,7 +198,6 @@ def model_schema(
|
||||
|
||||
|
||||
def get_field_info_schema(field: ModelField, schema_overrides: bool = False) -> Tuple[Dict[str, Any], bool]:
|
||||
|
||||
# If no title is explicitly set, we don't set title in the schema for enums.
|
||||
# The behaviour is the same as `BaseModel` reference, where the default title
|
||||
# is in the definitions part of the schema.
|
||||
@@ -379,7 +378,7 @@ def get_flat_models_from_field(field: ModelField, known_models: TypeModelSet) ->
|
||||
:param known_models: used to solve circular references
|
||||
:return: a set with the model used in the declaration for this field, if any, and all its sub-models
|
||||
"""
|
||||
from .main import BaseModel
|
||||
from pydantic.v1.main import BaseModel
|
||||
|
||||
flat_models: TypeModelSet = set()
|
||||
|
||||
@@ -446,7 +445,7 @@ def field_type_schema(
|
||||
Take a single ``field`` and generate the schema for its type only, not including additional
|
||||
information as title, etc. Also return additional schema definitions, from sub-models.
|
||||
"""
|
||||
from .main import BaseModel # noqa: F811
|
||||
from pydantic.v1.main import BaseModel # noqa: F811
|
||||
|
||||
definitions = {}
|
||||
nested_models: Set[str] = set()
|
||||
@@ -739,7 +738,7 @@ def field_singleton_sub_fields_schema(
|
||||
discriminator_models_refs[discriminator_value] = discriminator_model_ref['$ref']
|
||||
|
||||
s['discriminator'] = {
|
||||
'propertyName': field.discriminator_alias,
|
||||
'propertyName': field.discriminator_alias if by_alias else field.discriminator_key,
|
||||
'mapping': discriminator_models_refs,
|
||||
}
|
||||
|
||||
@@ -839,7 +838,7 @@ def field_singleton_schema( # noqa: C901 (ignore complexity)
|
||||
|
||||
Take a single Pydantic ``ModelField``, and return its schema and any additional definitions from sub-models.
|
||||
"""
|
||||
from .main import BaseModel
|
||||
from pydantic.v1.main import BaseModel
|
||||
|
||||
definitions: Dict[str, Any] = {}
|
||||
nested_models: Set[str] = set()
|
||||
@@ -975,7 +974,7 @@ def multitypes_literal_field_for_schema(values: Tuple[Any, ...], field: ModelFie
|
||||
|
||||
|
||||
def encode_default(dft: Any) -> Any:
|
||||
from .main import BaseModel
|
||||
from pydantic.v1.main import BaseModel
|
||||
|
||||
if isinstance(dft, BaseModel) or is_dataclass(dft):
|
||||
dft = cast('dict[str, Any]', pydantic_encoder(dft))
|
||||
@@ -1091,7 +1090,7 @@ def get_annotation_with_constraints(annotation: Any, field_info: FieldInfo) -> T
|
||||
if issubclass(type_, (SecretStr, SecretBytes)):
|
||||
attrs = ('max_length', 'min_length')
|
||||
|
||||
def constraint_func(**kw: Any) -> Type[Any]:
|
||||
def constraint_func(**kw: Any) -> Type[Any]: # noqa: F811
|
||||
return type(type_.__name__, (type_,), kw)
|
||||
|
||||
elif issubclass(type_, str) and not issubclass(type_, (EmailStr, AnyUrl)):
|
||||
|
||||
@@ -3,16 +3,16 @@ from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Callable, Optional, Type, TypeVar, Union
|
||||
|
||||
from .parse import Protocol, load_file, load_str_bytes
|
||||
from .types import StrBytes
|
||||
from .typing import display_as_type
|
||||
from pydantic.v1.parse import Protocol, load_file, load_str_bytes
|
||||
from pydantic.v1.types import StrBytes
|
||||
from pydantic.v1.typing import display_as_type
|
||||
|
||||
__all__ = ('parse_file_as', 'parse_obj_as', 'parse_raw_as', 'schema_of', 'schema_json_of')
|
||||
|
||||
NameFactory = Union[str, Callable[[Type[Any]], str]]
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .typing import DictStrAny
|
||||
from pydantic.v1.typing import DictStrAny
|
||||
|
||||
|
||||
def _generate_parsing_type_name(type_: Any) -> str:
|
||||
@@ -21,7 +21,7 @@ def _generate_parsing_type_name(type_: Any) -> str:
|
||||
|
||||
@lru_cache(maxsize=2048)
|
||||
def _get_parsing_type(type_: Any, *, type_name: Optional[NameFactory] = None) -> Any:
|
||||
from .main import create_model
|
||||
from pydantic.v1.main import create_model
|
||||
|
||||
if type_name is None:
|
||||
type_name = _generate_parsing_type_name
|
||||
|
||||
@@ -28,10 +28,10 @@ from typing import (
|
||||
from uuid import UUID
|
||||
from weakref import WeakSet
|
||||
|
||||
from . import errors
|
||||
from .datetime_parse import parse_date
|
||||
from .utils import import_string, update_not_none
|
||||
from .validators import (
|
||||
from pydantic.v1 import errors
|
||||
from pydantic.v1.datetime_parse import parse_date
|
||||
from pydantic.v1.utils import import_string, update_not_none
|
||||
from pydantic.v1.validators import (
|
||||
bytes_validator,
|
||||
constr_length_validator,
|
||||
constr_lower,
|
||||
@@ -123,9 +123,9 @@ StrIntFloat = Union[str, int, float]
|
||||
if TYPE_CHECKING:
|
||||
from typing_extensions import Annotated
|
||||
|
||||
from .dataclasses import Dataclass
|
||||
from .main import BaseModel
|
||||
from .typing import CallableGenerator
|
||||
from pydantic.v1.dataclasses import Dataclass
|
||||
from pydantic.v1.main import BaseModel
|
||||
from pydantic.v1.typing import CallableGenerator
|
||||
|
||||
ModelOrDc = Type[Union[BaseModel, Dataclass]]
|
||||
|
||||
@@ -481,6 +481,7 @@ else:
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SET TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
||||
# This types superclass should be Set[T], but cython chokes on that...
|
||||
class ConstrainedSet(set): # type: ignore
|
||||
# Needed for pydantic to detect that this is a set
|
||||
@@ -569,6 +570,7 @@ def confrozenset(
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ LIST TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
||||
# This types superclass should be List[T], but cython chokes on that...
|
||||
class ConstrainedList(list): # type: ignore
|
||||
# Needed for pydantic to detect that this is a list
|
||||
@@ -827,7 +829,7 @@ class JsonWrapper:
|
||||
class JsonMeta(type):
|
||||
def __getitem__(self, t: Type[Any]) -> Type[JsonWrapper]:
|
||||
if t is Any:
|
||||
return Json # allow Json[Any] to replecate plain Json
|
||||
return Json # allow Json[Any] to replicate plain Json
|
||||
return _registered(type('JsonWrapperValue', (JsonWrapper,), {'inner_type': t}))
|
||||
|
||||
|
||||
@@ -1094,7 +1096,6 @@ class ByteSize(int):
|
||||
|
||||
@classmethod
|
||||
def validate(cls, v: StrIntFloat) -> 'ByteSize':
|
||||
|
||||
try:
|
||||
return cls(int(v))
|
||||
except ValueError:
|
||||
@@ -1116,7 +1117,6 @@ class ByteSize(int):
|
||||
return cls(int(float(scalar) * unit_mult))
|
||||
|
||||
def human_readable(self, decimal: bool = False) -> str:
|
||||
|
||||
if decimal:
|
||||
divisor = 1000
|
||||
units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
|
||||
@@ -1135,7 +1135,6 @@ class ByteSize(int):
|
||||
return f'{num:0.1f}{final_unit}'
|
||||
|
||||
def to(self, unit: str) -> float:
|
||||
|
||||
try:
|
||||
unit_div = BYTE_SIZES[unit.lower()]
|
||||
except KeyError:
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import functools
|
||||
import operator
|
||||
import sys
|
||||
import typing
|
||||
from collections.abc import Callable
|
||||
@@ -58,12 +60,21 @@ if sys.version_info < (3, 9):
|
||||
def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any:
|
||||
return type_._evaluate(globalns, localns)
|
||||
|
||||
else:
|
||||
elif sys.version_info < (3, 12, 4):
|
||||
|
||||
def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any:
|
||||
# Even though it is the right signature for python 3.9, mypy complains with
|
||||
# `error: Too many arguments for "_evaluate" of "ForwardRef"` hence the cast...
|
||||
return cast(Any, type_)._evaluate(globalns, localns, set())
|
||||
# Python 3.13/3.12.4+ made `recursive_guard` a kwarg, so name it explicitly to avoid:
|
||||
# TypeError: ForwardRef._evaluate() missing 1 required keyword-only argument: 'recursive_guard'
|
||||
return cast(Any, type_)._evaluate(globalns, localns, recursive_guard=set())
|
||||
|
||||
else:
|
||||
|
||||
def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any:
|
||||
# Pydantic 1.x will not support PEP 695 syntax, but provide `type_params` to avoid
|
||||
# warnings:
|
||||
return cast(Any, type_)._evaluate(globalns, localns, type_params=(), recursive_guard=set())
|
||||
|
||||
|
||||
if sys.version_info < (3, 9):
|
||||
@@ -190,9 +201,6 @@ if sys.version_info < (3, 9):
|
||||
return tp
|
||||
|
||||
else:
|
||||
from typing import _UnionGenericAlias # type: ignore
|
||||
|
||||
from typing_extensions import _AnnotatedAlias
|
||||
|
||||
def convert_generics(tp: Type[Any]) -> Type[Any]:
|
||||
"""
|
||||
@@ -212,7 +220,7 @@ else:
|
||||
|
||||
# typing.Annotated needs special treatment
|
||||
if origin is Annotated:
|
||||
return _AnnotatedAlias(convert_generics(args[0]), args[1:])
|
||||
return Annotated[(convert_generics(args[0]), *args[1:])] # type: ignore
|
||||
|
||||
# recursively replace `str` instances inside of `GenericAlias` with `ForwardRef(arg)`
|
||||
converted = tuple(
|
||||
@@ -226,7 +234,7 @@ else:
|
||||
return TypingGenericAlias(origin, converted)
|
||||
elif isinstance(tp, TypesUnionType):
|
||||
# recreate types.UnionType (PEP604, Python >= 3.10)
|
||||
return _UnionGenericAlias(origin, converted)
|
||||
return functools.reduce(operator.or_, converted) # type: ignore
|
||||
else:
|
||||
try:
|
||||
setattr(tp, '__args__', converted)
|
||||
@@ -256,7 +264,7 @@ StrPath = Union[str, PathLike]
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .fields import ModelField
|
||||
from pydantic.v1.fields import ModelField
|
||||
|
||||
TupleGenerator = Generator[Tuple[str, Any], None, None]
|
||||
DictStrAny = Dict[str, Any]
|
||||
@@ -397,7 +405,10 @@ def resolve_annotations(raw_annotations: Dict[str, Type[Any]], module_name: Opti
|
||||
else:
|
||||
value = ForwardRef(value, is_argument=False)
|
||||
try:
|
||||
value = _eval_type(value, base_globals, None)
|
||||
if sys.version_info >= (3, 13):
|
||||
value = _eval_type(value, base_globals, None, type_params=())
|
||||
else:
|
||||
value = _eval_type(value, base_globals, None)
|
||||
except NameError:
|
||||
# this is ok, it can be fixed with update_forward_refs
|
||||
pass
|
||||
@@ -435,7 +446,7 @@ def is_namedtuple(type_: Type[Any]) -> bool:
|
||||
Check if a given class is a named tuple.
|
||||
It can be either a `typing.NamedTuple` or `collections.namedtuple`
|
||||
"""
|
||||
from .utils import lenient_issubclass
|
||||
from pydantic.v1.utils import lenient_issubclass
|
||||
|
||||
return lenient_issubclass(type_, tuple) and hasattr(type_, '_fields')
|
||||
|
||||
@@ -445,7 +456,7 @@ def is_typeddict(type_: Type[Any]) -> bool:
|
||||
Check if a given class is a typed dict (from `typing` or `typing_extensions`)
|
||||
In 3.10, there will be a public method (https://docs.python.org/3.10/library/typing.html#typing.is_typeddict)
|
||||
"""
|
||||
from .utils import lenient_issubclass
|
||||
from pydantic.v1.utils import lenient_issubclass
|
||||
|
||||
return lenient_issubclass(type_, dict) and hasattr(type_, '__total__')
|
||||
|
||||
|
||||
@@ -28,8 +28,8 @@ from typing import (
|
||||
|
||||
from typing_extensions import Annotated
|
||||
|
||||
from .errors import ConfigError
|
||||
from .typing import (
|
||||
from pydantic.v1.errors import ConfigError
|
||||
from pydantic.v1.typing import (
|
||||
NoneType,
|
||||
WithArgsTypes,
|
||||
all_literal_values,
|
||||
@@ -39,17 +39,17 @@ from .typing import (
|
||||
is_literal_type,
|
||||
is_union,
|
||||
)
|
||||
from .version import version_info
|
||||
from pydantic.v1.version import version_info
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from inspect import Signature
|
||||
from pathlib import Path
|
||||
|
||||
from .config import BaseConfig
|
||||
from .dataclasses import Dataclass
|
||||
from .fields import ModelField
|
||||
from .main import BaseModel
|
||||
from .typing import AbstractSetIntStr, DictIntStrAny, IntStr, MappingIntStrAny, ReprArgs
|
||||
from pydantic.v1.config import BaseConfig
|
||||
from pydantic.v1.dataclasses import Dataclass
|
||||
from pydantic.v1.fields import ModelField
|
||||
from pydantic.v1.main import BaseModel
|
||||
from pydantic.v1.typing import AbstractSetIntStr, DictIntStrAny, IntStr, MappingIntStrAny, ReprArgs
|
||||
|
||||
RichReprResult = Iterable[Union[Any, Tuple[Any], Tuple[str, Any], Tuple[str, Any, Any]]]
|
||||
|
||||
@@ -66,6 +66,7 @@ __all__ = (
|
||||
'almost_equal_floats',
|
||||
'get_model',
|
||||
'to_camel',
|
||||
'to_lower_camel',
|
||||
'is_valid_field',
|
||||
'smart_deepcopy',
|
||||
'PyObjectStr',
|
||||
@@ -158,7 +159,7 @@ def sequence_like(v: Any) -> bool:
|
||||
return isinstance(v, (list, tuple, set, frozenset, GeneratorType, deque))
|
||||
|
||||
|
||||
def validate_field_name(bases: List[Type['BaseModel']], field_name: str) -> None:
|
||||
def validate_field_name(bases: Iterable[Type[Any]], field_name: str) -> None:
|
||||
"""
|
||||
Ensure that the field's name does not shadow an existing attribute of the model.
|
||||
"""
|
||||
@@ -240,7 +241,7 @@ def generate_model_signature(
|
||||
"""
|
||||
from inspect import Parameter, Signature, signature
|
||||
|
||||
from .config import Extra
|
||||
from pydantic.v1.config import Extra
|
||||
|
||||
present_params = signature(init).parameters.values()
|
||||
merged_params: Dict[str, Parameter] = {}
|
||||
@@ -298,7 +299,7 @@ def generate_model_signature(
|
||||
|
||||
|
||||
def get_model(obj: Union[Type['BaseModel'], Type['Dataclass']]) -> Type['BaseModel']:
|
||||
from .main import BaseModel
|
||||
from pydantic.v1.main import BaseModel
|
||||
|
||||
try:
|
||||
model_cls = obj.__pydantic_model__ # type: ignore
|
||||
@@ -707,6 +708,8 @@ DUNDER_ATTRIBUTES = {
|
||||
'__orig_bases__',
|
||||
'__orig_class__',
|
||||
'__qualname__',
|
||||
'__firstlineno__',
|
||||
'__static_attributes__',
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -27,10 +27,11 @@ from typing import (
|
||||
Union,
|
||||
)
|
||||
from uuid import UUID
|
||||
from warnings import warn
|
||||
|
||||
from . import errors
|
||||
from .datetime_parse import parse_date, parse_datetime, parse_duration, parse_time
|
||||
from .typing import (
|
||||
from pydantic.v1 import errors
|
||||
from pydantic.v1.datetime_parse import parse_date, parse_datetime, parse_duration, parse_time
|
||||
from pydantic.v1.typing import (
|
||||
AnyCallable,
|
||||
all_literal_values,
|
||||
display_as_type,
|
||||
@@ -41,14 +42,14 @@ from .typing import (
|
||||
is_none_type,
|
||||
is_typeddict,
|
||||
)
|
||||
from .utils import almost_equal_floats, lenient_issubclass, sequence_like
|
||||
from pydantic.v1.utils import almost_equal_floats, lenient_issubclass, sequence_like
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing_extensions import Literal, TypedDict
|
||||
|
||||
from .config import BaseConfig
|
||||
from .fields import ModelField
|
||||
from .types import ConstrainedDecimal, ConstrainedFloat, ConstrainedInt
|
||||
from pydantic.v1.config import BaseConfig
|
||||
from pydantic.v1.fields import ModelField
|
||||
from pydantic.v1.types import ConstrainedDecimal, ConstrainedFloat, ConstrainedInt
|
||||
|
||||
ConstrainedNumber = Union[ConstrainedDecimal, ConstrainedFloat, ConstrainedInt]
|
||||
AnyOrderedDict = OrderedDict[Any, Any]
|
||||
@@ -594,7 +595,7 @@ NamedTupleT = TypeVar('NamedTupleT', bound=NamedTuple)
|
||||
def make_namedtuple_validator(
|
||||
namedtuple_cls: Type[NamedTupleT], config: Type['BaseConfig']
|
||||
) -> Callable[[Tuple[Any, ...]], NamedTupleT]:
|
||||
from .annotated_types import create_model_from_namedtuple
|
||||
from pydantic.v1.annotated_types import create_model_from_namedtuple
|
||||
|
||||
NamedTupleModel = create_model_from_namedtuple(
|
||||
namedtuple_cls,
|
||||
@@ -619,7 +620,7 @@ def make_namedtuple_validator(
|
||||
def make_typeddict_validator(
|
||||
typeddict_cls: Type['TypedDict'], config: Type['BaseConfig'] # type: ignore[valid-type]
|
||||
) -> Callable[[Any], Dict[str, Any]]:
|
||||
from .annotated_types import create_model_from_typeddict
|
||||
from pydantic.v1.annotated_types import create_model_from_typeddict
|
||||
|
||||
TypedDictModel = create_model_from_typeddict(
|
||||
typeddict_cls,
|
||||
@@ -698,7 +699,7 @@ _VALIDATORS: List[Tuple[Type[Any], List[Any]]] = [
|
||||
def find_validators( # noqa: C901 (ignore complexity)
|
||||
type_: Type[Any], config: Type['BaseConfig']
|
||||
) -> Generator[AnyCallable, None, None]:
|
||||
from .dataclasses import is_builtin_dataclass, make_dataclass_validator
|
||||
from pydantic.v1.dataclasses import is_builtin_dataclass, make_dataclass_validator
|
||||
|
||||
if type_ is Any or type_ is object:
|
||||
return
|
||||
@@ -762,4 +763,6 @@ def find_validators( # noqa: C901 (ignore complexity)
|
||||
if config.arbitrary_types_allowed:
|
||||
yield make_arbitrary_type_validator(type_)
|
||||
else:
|
||||
if hasattr(type_, '__pydantic_core_schema__'):
|
||||
warn(f'Mixing V1 and V2 models is not supported. `{type_.__name__}` is a V2 model.', UserWarning)
|
||||
raise RuntimeError(f'no validator found for {type_}, see `arbitrary_types_allowed` in Config')
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
__all__ = 'compiled', 'VERSION', 'version_info'
|
||||
|
||||
VERSION = '1.10.13'
|
||||
VERSION = '1.10.21'
|
||||
|
||||
try:
|
||||
import cython # type: ignore
|
||||
|
||||
Reference in New Issue
Block a user