mirror of
https://github.com/Tautulli/Tautulli.git
synced 2025-07-06 05:01:14 -07:00
Update cherrypy==18.9.0
This commit is contained in:
parent
2fc618c01f
commit
51196a7fb1
137 changed files with 44442 additions and 11582 deletions
|
@ -1,479 +1,327 @@
|
|||
"""
|
||||
The main purpose is to enhance stdlib dataclasses by adding validation
|
||||
A pydantic dataclass can be generated from scratch or from a stdlib one.
|
||||
"""Provide an enhanced dataclass that performs validation."""
|
||||
from __future__ import annotations as _annotations
|
||||
|
||||
Behind the scene, a pydantic dataclass is just like a regular one on which we attach
|
||||
a `BaseModel` and magic methods to trigger the validation of the data.
|
||||
`__init__` and `__post_init__` are hence overridden and have extra logic to be
|
||||
able to validate input data.
|
||||
|
||||
When a pydantic dataclass is generated from scratch, it's just a plain dataclass
|
||||
with validation triggered at initialization
|
||||
|
||||
The tricky part if for stdlib dataclasses that are converted after into pydantic ones e.g.
|
||||
|
||||
```py
|
||||
@dataclasses.dataclass
|
||||
class M:
|
||||
x: int
|
||||
|
||||
ValidatedM = pydantic.dataclasses.dataclass(M)
|
||||
```
|
||||
|
||||
We indeed still want to support equality, hashing, repr, ... as if it was the stdlib one!
|
||||
|
||||
```py
|
||||
assert isinstance(ValidatedM(x=1), M)
|
||||
assert ValidatedM(x=1) == M(x=1)
|
||||
```
|
||||
|
||||
This means we **don't want to create a new dataclass that inherits from it**
|
||||
The trick is to create a wrapper around `M` that will act as a proxy to trigger
|
||||
validation without altering default `M` behaviour.
|
||||
"""
|
||||
import dataclasses
|
||||
import sys
|
||||
from contextlib import contextmanager
|
||||
from functools import wraps
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Callable,
|
||||
ClassVar,
|
||||
Dict,
|
||||
Generator,
|
||||
Optional,
|
||||
Set,
|
||||
Type,
|
||||
TypeVar,
|
||||
Union,
|
||||
overload,
|
||||
)
|
||||
import types
|
||||
from typing import TYPE_CHECKING, Any, Callable, Generic, NoReturn, TypeVar, overload
|
||||
|
||||
from typing_extensions import dataclass_transform
|
||||
from typing_extensions import Literal, TypeGuard, 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 ._internal import _config, _decorators, _typing_extra
|
||||
from ._internal import _dataclasses as _pydantic_dataclasses
|
||||
from ._migration import getattr_migration
|
||||
from .config import ConfigDict
|
||||
from .fields import Field, FieldInfo
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .main import BaseModel
|
||||
from .typing import CallableGenerator, NoArgAnyCallable
|
||||
from ._internal._dataclasses import PydanticDataclass
|
||||
|
||||
DataclassT = TypeVar('DataclassT', bound='Dataclass')
|
||||
|
||||
DataclassClassOrWrapper = Union[Type['Dataclass'], 'DataclassProxy']
|
||||
|
||||
class Dataclass:
|
||||
# stdlib attributes
|
||||
__dataclass_fields__: ClassVar[Dict[str, Any]]
|
||||
__dataclass_params__: ClassVar[Any] # in reality `dataclasses._DataclassParams`
|
||||
__post_init__: ClassVar[Callable[..., None]]
|
||||
|
||||
# Added by pydantic
|
||||
__pydantic_run_validation__: ClassVar[bool]
|
||||
__post_init_post_parse__: ClassVar[Callable[..., None]]
|
||||
__pydantic_initialised__: ClassVar[bool]
|
||||
__pydantic_model__: ClassVar[Type[BaseModel]]
|
||||
__pydantic_validate_values__: ClassVar[Callable[['Dataclass'], None]]
|
||||
__pydantic_has_field_info_default__: ClassVar[bool] # whether a `pydantic.Field` is used as default value
|
||||
|
||||
def __init__(self, *args: object, **kwargs: object) -> None:
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def __get_validators__(cls: Type['Dataclass']) -> 'CallableGenerator':
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def __validate__(cls: Type['DataclassT'], v: Any) -> 'DataclassT':
|
||||
pass
|
||||
|
||||
|
||||
__all__ = [
|
||||
'dataclass',
|
||||
'set_validation',
|
||||
'create_pydantic_model_from_dataclass',
|
||||
'is_builtin_dataclass',
|
||||
'make_dataclass_validator',
|
||||
]
|
||||
__all__ = 'dataclass', 'rebuild_dataclass'
|
||||
|
||||
_T = TypeVar('_T')
|
||||
|
||||
if sys.version_info >= (3, 10):
|
||||
|
||||
@dataclass_transform(kw_only_default=True, field_descriptors=(Field, FieldInfo))
|
||||
@dataclass_transform(field_specifiers=(dataclasses.field, Field))
|
||||
@overload
|
||||
def dataclass(
|
||||
*,
|
||||
init: bool = True,
|
||||
init: Literal[False] = False,
|
||||
repr: bool = True,
|
||||
eq: bool = True,
|
||||
order: bool = False,
|
||||
unsafe_hash: bool = False,
|
||||
frozen: bool = False,
|
||||
config: Union[ConfigDict, Type[object], None] = None,
|
||||
validate_on_init: Optional[bool] = None,
|
||||
config: ConfigDict | type[object] | None = None,
|
||||
validate_on_init: bool | None = None,
|
||||
kw_only: bool = ...,
|
||||
) -> Callable[[Type[_T]], 'DataclassClassOrWrapper']:
|
||||
slots: bool = ...,
|
||||
) -> Callable[[type[_T]], type[PydanticDataclass]]: # type: ignore
|
||||
...
|
||||
|
||||
@dataclass_transform(kw_only_default=True, field_descriptors=(Field, FieldInfo))
|
||||
@dataclass_transform(field_specifiers=(dataclasses.field, Field))
|
||||
@overload
|
||||
def dataclass(
|
||||
_cls: Type[_T],
|
||||
_cls: type[_T], # type: ignore
|
||||
*,
|
||||
init: bool = True,
|
||||
init: Literal[False] = False,
|
||||
repr: bool = True,
|
||||
eq: bool = True,
|
||||
order: bool = False,
|
||||
unsafe_hash: bool = False,
|
||||
frozen: bool = False,
|
||||
config: Union[ConfigDict, Type[object], None] = None,
|
||||
validate_on_init: Optional[bool] = None,
|
||||
config: ConfigDict | type[object] | None = None,
|
||||
validate_on_init: bool | None = None,
|
||||
kw_only: bool = ...,
|
||||
) -> 'DataclassClassOrWrapper':
|
||||
slots: bool = ...,
|
||||
) -> type[PydanticDataclass]:
|
||||
...
|
||||
|
||||
else:
|
||||
|
||||
@dataclass_transform(kw_only_default=True, field_descriptors=(Field, FieldInfo))
|
||||
@dataclass_transform(field_specifiers=(dataclasses.field, Field))
|
||||
@overload
|
||||
def dataclass(
|
||||
*,
|
||||
init: bool = True,
|
||||
init: Literal[False] = False,
|
||||
repr: bool = True,
|
||||
eq: bool = True,
|
||||
order: bool = False,
|
||||
unsafe_hash: bool = False,
|
||||
frozen: bool = False,
|
||||
config: Union[ConfigDict, Type[object], None] = None,
|
||||
validate_on_init: Optional[bool] = None,
|
||||
) -> Callable[[Type[_T]], 'DataclassClassOrWrapper']:
|
||||
config: ConfigDict | type[object] | None = None,
|
||||
validate_on_init: bool | None = None,
|
||||
) -> Callable[[type[_T]], type[PydanticDataclass]]: # type: ignore
|
||||
...
|
||||
|
||||
@dataclass_transform(kw_only_default=True, field_descriptors=(Field, FieldInfo))
|
||||
@dataclass_transform(field_specifiers=(dataclasses.field, Field))
|
||||
@overload
|
||||
def dataclass(
|
||||
_cls: Type[_T],
|
||||
_cls: type[_T], # type: ignore
|
||||
*,
|
||||
init: bool = True,
|
||||
init: Literal[False] = False,
|
||||
repr: bool = True,
|
||||
eq: bool = True,
|
||||
order: bool = False,
|
||||
unsafe_hash: bool = False,
|
||||
frozen: bool = False,
|
||||
config: Union[ConfigDict, Type[object], None] = None,
|
||||
validate_on_init: Optional[bool] = None,
|
||||
) -> 'DataclassClassOrWrapper':
|
||||
config: ConfigDict | type[object] | None = None,
|
||||
validate_on_init: bool | None = None,
|
||||
) -> type[PydanticDataclass]:
|
||||
...
|
||||
|
||||
|
||||
@dataclass_transform(kw_only_default=True, field_descriptors=(Field, FieldInfo))
|
||||
def dataclass(
|
||||
_cls: Optional[Type[_T]] = None,
|
||||
@dataclass_transform(field_specifiers=(dataclasses.field, Field))
|
||||
def dataclass( # noqa: C901
|
||||
_cls: type[_T] | None = None,
|
||||
*,
|
||||
init: bool = True,
|
||||
init: Literal[False] = False,
|
||||
repr: bool = True,
|
||||
eq: bool = True,
|
||||
order: bool = False,
|
||||
unsafe_hash: bool = False,
|
||||
frozen: bool = False,
|
||||
config: Union[ConfigDict, Type[object], None] = None,
|
||||
validate_on_init: Optional[bool] = None,
|
||||
config: ConfigDict | type[object] | None = None,
|
||||
validate_on_init: bool | None = None,
|
||||
kw_only: bool = False,
|
||||
) -> Union[Callable[[Type[_T]], 'DataclassClassOrWrapper'], 'DataclassClassOrWrapper']:
|
||||
slots: bool = False,
|
||||
) -> Callable[[type[_T]], type[PydanticDataclass]] | type[PydanticDataclass]:
|
||||
"""Usage docs: https://docs.pydantic.dev/2.6/concepts/dataclasses/
|
||||
|
||||
A decorator used to create a Pydantic-enhanced dataclass, similar to the standard Python `dataclass`,
|
||||
but with added validation.
|
||||
|
||||
This function should be used similarly to `dataclasses.dataclass`.
|
||||
|
||||
Args:
|
||||
_cls: The target `dataclass`.
|
||||
init: Included for signature compatibility with `dataclasses.dataclass`, and is passed through to
|
||||
`dataclasses.dataclass` when appropriate. If specified, must be set to `False`, as pydantic inserts its
|
||||
own `__init__` function.
|
||||
repr: A boolean indicating whether to include the field in the `__repr__` output.
|
||||
eq: Determines if a `__eq__` method should be generated for the class.
|
||||
order: Determines if comparison magic methods should be generated, such as `__lt__`, but not `__eq__`.
|
||||
unsafe_hash: Determines if a `__hash__` method should be included in the class, as in `dataclasses.dataclass`.
|
||||
frozen: Determines if the generated class should be a 'frozen' `dataclass`, which does not allow its
|
||||
attributes to be modified after it has been initialized.
|
||||
config: The Pydantic config to use for the `dataclass`.
|
||||
validate_on_init: A deprecated parameter included for backwards compatibility; in V2, all Pydantic dataclasses
|
||||
are validated on init.
|
||||
kw_only: Determines if `__init__` method parameters must be specified by keyword only. Defaults to `False`.
|
||||
slots: Determines if the generated class should be a 'slots' `dataclass`, which does not allow the addition of
|
||||
new attributes after instantiation.
|
||||
|
||||
Returns:
|
||||
A decorator that accepts a class as its argument and returns a Pydantic `dataclass`.
|
||||
|
||||
Raises:
|
||||
AssertionError: Raised if `init` is not `False` or `validate_on_init` is `False`.
|
||||
"""
|
||||
Like the python standard lib dataclasses but with type validation.
|
||||
The result is either a pydantic dataclass that will validate input data
|
||||
or a wrapper that will trigger validation around a stdlib dataclass
|
||||
to avoid modifying it directly
|
||||
"""
|
||||
the_config = get_config(config)
|
||||
assert init is False, 'pydantic.dataclasses.dataclass only supports init=False'
|
||||
assert validate_on_init is not False, 'validate_on_init=False is no longer supported'
|
||||
|
||||
def wrap(cls: Type[Any]) -> 'DataclassClassOrWrapper':
|
||||
import dataclasses
|
||||
if sys.version_info >= (3, 10):
|
||||
kwargs = dict(kw_only=kw_only, slots=slots)
|
||||
else:
|
||||
kwargs = {}
|
||||
|
||||
if is_builtin_dataclass(cls) and _extra_dc_args(_cls) == _extra_dc_args(_cls.__bases__[0]): # type: ignore
|
||||
dc_cls_doc = ''
|
||||
dc_cls = DataclassProxy(cls)
|
||||
default_validate_on_init = False
|
||||
else:
|
||||
dc_cls_doc = cls.__doc__ or '' # needs to be done before generating dataclass
|
||||
if sys.version_info >= (3, 10):
|
||||
dc_cls = dataclasses.dataclass(
|
||||
cls,
|
||||
init=init,
|
||||
repr=repr,
|
||||
eq=eq,
|
||||
order=order,
|
||||
unsafe_hash=unsafe_hash,
|
||||
frozen=frozen,
|
||||
kw_only=kw_only,
|
||||
)
|
||||
else:
|
||||
dc_cls = dataclasses.dataclass( # type: ignore
|
||||
cls, init=init, repr=repr, eq=eq, order=order, unsafe_hash=unsafe_hash, frozen=frozen
|
||||
)
|
||||
default_validate_on_init = True
|
||||
def make_pydantic_fields_compatible(cls: type[Any]) -> None:
|
||||
"""Make sure that stdlib `dataclasses` understands `Field` kwargs like `kw_only`
|
||||
To do that, we simply change
|
||||
`x: int = pydantic.Field(..., kw_only=True)`
|
||||
into
|
||||
`x: int = dataclasses.field(default=pydantic.Field(..., kw_only=True), kw_only=True)`
|
||||
"""
|
||||
for annotation_cls in cls.__mro__:
|
||||
# In Python < 3.9, `__annotations__` might not be present if there are no fields.
|
||||
# we therefore need to use `getattr` to avoid an `AttributeError`.
|
||||
annotations = getattr(annotation_cls, '__annotations__', [])
|
||||
for field_name in annotations:
|
||||
field_value = getattr(cls, field_name, None)
|
||||
# Process only if this is an instance of `FieldInfo`.
|
||||
if not isinstance(field_value, FieldInfo):
|
||||
continue
|
||||
|
||||
should_validate_on_init = default_validate_on_init if validate_on_init is None else validate_on_init
|
||||
_add_pydantic_validation_attributes(cls, the_config, should_validate_on_init, dc_cls_doc)
|
||||
dc_cls.__pydantic_model__.__try_update_forward_refs__(**{cls.__name__: cls})
|
||||
return dc_cls
|
||||
# Initialize arguments for the standard `dataclasses.field`.
|
||||
field_args: dict = {'default': field_value}
|
||||
|
||||
# Handle `kw_only` for Python 3.10+
|
||||
if sys.version_info >= (3, 10) and field_value.kw_only:
|
||||
field_args['kw_only'] = True
|
||||
|
||||
# Set `repr` attribute if it's explicitly specified to be not `True`.
|
||||
if field_value.repr is not True:
|
||||
field_args['repr'] = field_value.repr
|
||||
|
||||
setattr(cls, field_name, dataclasses.field(**field_args))
|
||||
# In Python 3.8, dataclasses checks cls.__dict__['__annotations__'] for annotations,
|
||||
# so we must make sure it's initialized before we add to it.
|
||||
if cls.__dict__.get('__annotations__') is None:
|
||||
cls.__annotations__ = {}
|
||||
cls.__annotations__[field_name] = annotations[field_name]
|
||||
|
||||
def create_dataclass(cls: type[Any]) -> type[PydanticDataclass]:
|
||||
"""Create a Pydantic dataclass from a regular dataclass.
|
||||
|
||||
Args:
|
||||
cls: The class to create the Pydantic dataclass from.
|
||||
|
||||
Returns:
|
||||
A Pydantic dataclass.
|
||||
"""
|
||||
original_cls = cls
|
||||
|
||||
config_dict = config
|
||||
if config_dict is None:
|
||||
# if not explicitly provided, read from the type
|
||||
cls_config = getattr(cls, '__pydantic_config__', None)
|
||||
if cls_config is not None:
|
||||
config_dict = cls_config
|
||||
config_wrapper = _config.ConfigWrapper(config_dict)
|
||||
decorators = _decorators.DecoratorInfos.build(cls)
|
||||
|
||||
# Keep track of the original __doc__ so that we can restore it after applying the dataclasses decorator
|
||||
# Otherwise, classes with no __doc__ will have their signature added into the JSON schema description,
|
||||
# since dataclasses.dataclass will set this as the __doc__
|
||||
original_doc = cls.__doc__
|
||||
|
||||
if _pydantic_dataclasses.is_builtin_dataclass(cls):
|
||||
# Don't preserve the docstring for vanilla dataclasses, as it may include the signature
|
||||
# This matches v1 behavior, and there was an explicit test for it
|
||||
original_doc = None
|
||||
|
||||
# We don't want to add validation to the existing std lib dataclass, so we will subclass it
|
||||
# If the class is generic, we need to make sure the subclass also inherits from Generic
|
||||
# with all the same parameters.
|
||||
bases = (cls,)
|
||||
if issubclass(cls, Generic):
|
||||
generic_base = Generic[cls.__parameters__] # type: ignore
|
||||
bases = bases + (generic_base,)
|
||||
cls = types.new_class(cls.__name__, bases)
|
||||
|
||||
make_pydantic_fields_compatible(cls)
|
||||
|
||||
cls = dataclasses.dataclass( # type: ignore[call-overload]
|
||||
cls,
|
||||
# the value of init here doesn't affect anything except that it makes it easier to generate a signature
|
||||
init=True,
|
||||
repr=repr,
|
||||
eq=eq,
|
||||
order=order,
|
||||
unsafe_hash=unsafe_hash,
|
||||
frozen=frozen,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
cls.__pydantic_decorators__ = decorators # type: ignore
|
||||
cls.__doc__ = original_doc
|
||||
cls.__module__ = original_cls.__module__
|
||||
cls.__qualname__ = original_cls.__qualname__
|
||||
pydantic_complete = _pydantic_dataclasses.complete_dataclass(
|
||||
cls, config_wrapper, raise_errors=False, types_namespace=None
|
||||
)
|
||||
cls.__pydantic_complete__ = pydantic_complete # type: ignore
|
||||
return cls
|
||||
|
||||
if _cls is None:
|
||||
return wrap
|
||||
return create_dataclass
|
||||
|
||||
return wrap(_cls)
|
||||
return create_dataclass(_cls)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def set_validation(cls: Type['DataclassT'], value: bool) -> Generator[Type['DataclassT'], None, None]:
|
||||
original_run_validation = cls.__pydantic_run_validation__
|
||||
try:
|
||||
cls.__pydantic_run_validation__ = value
|
||||
yield cls
|
||||
finally:
|
||||
cls.__pydantic_run_validation__ = original_run_validation
|
||||
__getattr__ = getattr_migration(__name__)
|
||||
|
||||
if (3, 8) <= sys.version_info < (3, 11):
|
||||
# Monkeypatch dataclasses.InitVar so that typing doesn't error if it occurs as a type when evaluating type hints
|
||||
# Starting in 3.11, typing.get_type_hints will not raise an error if the retrieved type hints are not callable.
|
||||
|
||||
def _call_initvar(*args: Any, **kwargs: Any) -> NoReturn:
|
||||
"""This function does nothing but raise an error that is as similar as possible to what you'd get
|
||||
if you were to try calling `InitVar[int]()` without this monkeypatch. The whole purpose is just
|
||||
to ensure typing._type_check does not error if the type hint evaluates to `InitVar[<parameter>]`.
|
||||
"""
|
||||
raise TypeError("'InitVar' object is not callable")
|
||||
|
||||
dataclasses.InitVar.__call__ = _call_initvar
|
||||
|
||||
|
||||
class DataclassProxy:
|
||||
__slots__ = '__dataclass__'
|
||||
def rebuild_dataclass(
|
||||
cls: type[PydanticDataclass],
|
||||
*,
|
||||
force: bool = False,
|
||||
raise_errors: bool = True,
|
||||
_parent_namespace_depth: int = 2,
|
||||
_types_namespace: dict[str, Any] | None = None,
|
||||
) -> bool | None:
|
||||
"""Try to rebuild the pydantic-core schema for the dataclass.
|
||||
|
||||
def __init__(self, dc_cls: Type['Dataclass']) -> None:
|
||||
object.__setattr__(self, '__dataclass__', dc_cls)
|
||||
This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
|
||||
the initial attempt to build the schema, and automatic rebuilding fails.
|
||||
|
||||
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
||||
with set_validation(self.__dataclass__, True):
|
||||
return self.__dataclass__(*args, **kwargs)
|
||||
This is analogous to `BaseModel.model_rebuild`.
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self.__dataclass__, name)
|
||||
Args:
|
||||
cls: The class to rebuild the pydantic-core schema for.
|
||||
force: Whether to force the rebuilding of the schema, defaults to `False`.
|
||||
raise_errors: Whether to raise errors, defaults to `True`.
|
||||
_parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
|
||||
_types_namespace: The types namespace, defaults to `None`.
|
||||
|
||||
def __instancecheck__(self, instance: Any) -> bool:
|
||||
return isinstance(instance, self.__dataclass__)
|
||||
|
||||
|
||||
def _add_pydantic_validation_attributes( # noqa: C901 (ignore complexity)
|
||||
dc_cls: Type['Dataclass'],
|
||||
config: Type[BaseConfig],
|
||||
validate_on_init: bool,
|
||||
dc_cls_doc: str,
|
||||
) -> None:
|
||||
Returns:
|
||||
Returns `None` if the schema is already "complete" and rebuilding was not required.
|
||||
If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
||||
"""
|
||||
We need to replace the right method. If no `__post_init__` has been set in the stdlib dataclass
|
||||
it won't even exist (code is generated on the fly by `dataclasses`)
|
||||
By default, we run validation after `__init__` or `__post_init__` if defined
|
||||
"""
|
||||
init = dc_cls.__init__
|
||||
|
||||
@wraps(init)
|
||||
def handle_extra_init(self: 'Dataclass', *args: Any, **kwargs: Any) -> None:
|
||||
if config.extra == Extra.ignore:
|
||||
init(self, *args, **{k: v for k, v in kwargs.items() if k in self.__dataclass_fields__})
|
||||
|
||||
elif config.extra == Extra.allow:
|
||||
for k, v in kwargs.items():
|
||||
self.__dict__.setdefault(k, v)
|
||||
init(self, *args, **{k: v for k, v in kwargs.items() if k in self.__dataclass_fields__})
|
||||
|
||||
else:
|
||||
init(self, *args, **kwargs)
|
||||
|
||||
if hasattr(dc_cls, '__post_init__'):
|
||||
post_init = dc_cls.__post_init__
|
||||
|
||||
@wraps(post_init)
|
||||
def new_post_init(self: 'Dataclass', *args: Any, **kwargs: Any) -> None:
|
||||
if config.post_init_call == 'before_validation':
|
||||
post_init(self, *args, **kwargs)
|
||||
|
||||
if self.__class__.__pydantic_run_validation__:
|
||||
self.__pydantic_validate_values__()
|
||||
if hasattr(self, '__post_init_post_parse__'):
|
||||
self.__post_init_post_parse__(*args, **kwargs)
|
||||
|
||||
if config.post_init_call == 'after_validation':
|
||||
post_init(self, *args, **kwargs)
|
||||
|
||||
setattr(dc_cls, '__init__', handle_extra_init)
|
||||
setattr(dc_cls, '__post_init__', new_post_init)
|
||||
|
||||
if not force and cls.__pydantic_complete__:
|
||||
return None
|
||||
else:
|
||||
|
||||
@wraps(init)
|
||||
def new_init(self: 'Dataclass', *args: Any, **kwargs: Any) -> None:
|
||||
handle_extra_init(self, *args, **kwargs)
|
||||
|
||||
if self.__class__.__pydantic_run_validation__:
|
||||
self.__pydantic_validate_values__()
|
||||
|
||||
if hasattr(self, '__post_init_post_parse__'):
|
||||
# We need to find again the initvars. To do that we use `__dataclass_fields__` instead of
|
||||
# public method `dataclasses.fields`
|
||||
import dataclasses
|
||||
|
||||
# get all initvars and their default values
|
||||
initvars_and_values: Dict[str, Any] = {}
|
||||
for i, f in enumerate(self.__class__.__dataclass_fields__.values()):
|
||||
if f._field_type is dataclasses._FIELD_INITVAR: # type: ignore[attr-defined]
|
||||
try:
|
||||
# set arg value by default
|
||||
initvars_and_values[f.name] = args[i]
|
||||
except IndexError:
|
||||
initvars_and_values[f.name] = kwargs.get(f.name, f.default)
|
||||
|
||||
self.__post_init_post_parse__(**initvars_and_values)
|
||||
|
||||
setattr(dc_cls, '__init__', new_init)
|
||||
|
||||
setattr(dc_cls, '__pydantic_run_validation__', ClassAttribute('__pydantic_run_validation__', validate_on_init))
|
||||
setattr(dc_cls, '__pydantic_initialised__', False)
|
||||
setattr(dc_cls, '__pydantic_model__', create_pydantic_model_from_dataclass(dc_cls, config, dc_cls_doc))
|
||||
setattr(dc_cls, '__pydantic_validate_values__', _dataclass_validate_values)
|
||||
setattr(dc_cls, '__validate__', classmethod(_validate_dataclass))
|
||||
setattr(dc_cls, '__get_validators__', classmethod(_get_validators))
|
||||
|
||||
if dc_cls.__pydantic_model__.__config__.validate_assignment and not dc_cls.__dataclass_params__.frozen:
|
||||
setattr(dc_cls, '__setattr__', _dataclass_validate_assignment_setattr)
|
||||
|
||||
|
||||
def _get_validators(cls: 'DataclassClassOrWrapper') -> 'CallableGenerator':
|
||||
yield cls.__validate__
|
||||
|
||||
|
||||
def _validate_dataclass(cls: Type['DataclassT'], v: Any) -> 'DataclassT':
|
||||
with set_validation(cls, True):
|
||||
if isinstance(v, cls):
|
||||
v.__pydantic_validate_values__()
|
||||
return v
|
||||
elif isinstance(v, (list, tuple)):
|
||||
return cls(*v)
|
||||
elif isinstance(v, dict):
|
||||
return cls(**v)
|
||||
if _types_namespace is not None:
|
||||
types_namespace: dict[str, Any] | None = _types_namespace.copy()
|
||||
else:
|
||||
raise DataclassTypeError(class_name=cls.__name__)
|
||||
if _parent_namespace_depth > 0:
|
||||
frame_parent_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth) or {}
|
||||
# Note: we may need to add something similar to cls.__pydantic_parent_namespace__ from BaseModel
|
||||
# here when implementing handling of recursive generics. See BaseModel.model_rebuild for reference.
|
||||
types_namespace = frame_parent_ns
|
||||
else:
|
||||
types_namespace = {}
|
||||
|
||||
types_namespace = _typing_extra.get_cls_types_namespace(cls, types_namespace)
|
||||
return _pydantic_dataclasses.complete_dataclass(
|
||||
cls,
|
||||
_config.ConfigWrapper(cls.__pydantic_config__, check=False),
|
||||
raise_errors=raise_errors,
|
||||
types_namespace=types_namespace,
|
||||
)
|
||||
|
||||
|
||||
def create_pydantic_model_from_dataclass(
|
||||
dc_cls: Type['Dataclass'],
|
||||
config: Type[Any] = BaseConfig,
|
||||
dc_cls_doc: Optional[str] = None,
|
||||
) -> Type['BaseModel']:
|
||||
import dataclasses
|
||||
def is_pydantic_dataclass(__cls: type[Any]) -> TypeGuard[type[PydanticDataclass]]:
|
||||
"""Whether a class is a pydantic dataclass.
|
||||
|
||||
field_definitions: Dict[str, Any] = {}
|
||||
for field in dataclasses.fields(dc_cls):
|
||||
default: Any = Undefined
|
||||
default_factory: Optional['NoArgAnyCallable'] = None
|
||||
field_info: FieldInfo
|
||||
Args:
|
||||
__cls: The class.
|
||||
|
||||
if field.default is not dataclasses.MISSING:
|
||||
default = field.default
|
||||
elif field.default_factory is not dataclasses.MISSING:
|
||||
default_factory = field.default_factory
|
||||
else:
|
||||
default = Required
|
||||
|
||||
if isinstance(default, FieldInfo):
|
||||
field_info = default
|
||||
dc_cls.__pydantic_has_field_info_default__ = True
|
||||
else:
|
||||
field_info = Field(default=default, default_factory=default_factory, **field.metadata)
|
||||
|
||||
field_definitions[field.name] = (field.type, field_info)
|
||||
|
||||
validators = gather_all_validators(dc_cls)
|
||||
model: Type['BaseModel'] = create_model(
|
||||
dc_cls.__name__,
|
||||
__config__=config,
|
||||
__module__=dc_cls.__module__,
|
||||
__validators__=validators,
|
||||
__cls_kwargs__={'__resolve_forward_refs__': False},
|
||||
**field_definitions,
|
||||
)
|
||||
model.__doc__ = dc_cls_doc if dc_cls_doc is not None else dc_cls.__doc__ or ''
|
||||
return model
|
||||
|
||||
|
||||
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
|
||||
if getattr(self, '__pydantic_initialised__'):
|
||||
return
|
||||
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)}
|
||||
else:
|
||||
input_data = self.__dict__
|
||||
d, _, validation_error = validate_model(self.__pydantic_model__, input_data, cls=self.__class__)
|
||||
if validation_error:
|
||||
raise validation_error
|
||||
self.__dict__.update(d)
|
||||
object.__setattr__(self, '__pydantic_initialised__', True)
|
||||
|
||||
|
||||
def _dataclass_validate_assignment_setattr(self: 'Dataclass', name: str, value: Any) -> None:
|
||||
if self.__pydantic_initialised__:
|
||||
d = dict(self.__dict__)
|
||||
d.pop(name, None)
|
||||
known_field = self.__pydantic_model__.__fields__.get(name, None)
|
||||
if known_field:
|
||||
value, error_ = known_field.validate(value, d, loc=name, cls=self.__class__)
|
||||
if error_:
|
||||
raise ValidationError([error_], self.__class__)
|
||||
|
||||
object.__setattr__(self, name, value)
|
||||
|
||||
|
||||
def _extra_dc_args(cls: Type[Any]) -> Set[str]:
|
||||
return {
|
||||
x
|
||||
for x in dir(cls)
|
||||
if x not in getattr(cls, '__dataclass_fields__', {}) and not (x.startswith('__') and x.endswith('__'))
|
||||
}
|
||||
|
||||
|
||||
def is_builtin_dataclass(_cls: Type[Any]) -> bool:
|
||||
Returns:
|
||||
`True` if the class is a pydantic dataclass, `False` otherwise.
|
||||
"""
|
||||
Whether a class is a stdlib dataclass
|
||||
(useful to discriminated a pydantic dataclass that is actually a wrapper around a stdlib dataclass)
|
||||
|
||||
we check that
|
||||
- `_cls` is a dataclass
|
||||
- `_cls` is not a processed pydantic dataclass (with a basemodel attached)
|
||||
- `_cls` is not a pydantic dataclass inheriting directly from a stdlib dataclass
|
||||
e.g.
|
||||
```
|
||||
@dataclasses.dataclass
|
||||
class A:
|
||||
x: int
|
||||
|
||||
@pydantic.dataclasses.dataclass
|
||||
class B(A):
|
||||
y: int
|
||||
```
|
||||
In this case, when we first check `B`, we make an extra check and look at the annotations ('y'),
|
||||
which won't be a superset of all the dataclass fields (only the stdlib fields i.e. 'x')
|
||||
"""
|
||||
import dataclasses
|
||||
|
||||
return (
|
||||
dataclasses.is_dataclass(_cls)
|
||||
and not hasattr(_cls, '__pydantic_model__')
|
||||
and set(_cls.__dataclass_fields__).issuperset(set(getattr(_cls, '__annotations__', {})))
|
||||
)
|
||||
|
||||
|
||||
def make_dataclass_validator(dc_cls: Type['Dataclass'], config: Type[BaseConfig]) -> 'CallableGenerator':
|
||||
"""
|
||||
Create a pydantic.dataclass from a builtin dataclass to add type validation
|
||||
and yield the validators
|
||||
It retrieves the parameters of the dataclass and forwards them to the newly created dataclass
|
||||
"""
|
||||
yield from _get_validators(dataclass(dc_cls, config=config, validate_on_init=False))
|
||||
return dataclasses.is_dataclass(__cls) and '__pydantic_validator__' in __cls.__dict__
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue