gt4py.eve.datamodels package
Submodules
gt4py.eve.datamodels.core module
Data Model class creation and other utils.
Check eve.datamodels
for additional information.
- gt4py.eve.datamodels.core.Coerced
Type hint marker to define fields that should be coerced at initialization.
alias of
gt4py.eve.datamodels.core._T
[gt4py.eve.datamodels.core._T
]
- gt4py.eve.datamodels.core.DEFAULT_OPTIONS: Final[utils.FrozenNamespace] = FrozenNamespace(repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, coerce=False, generic=False)
Convenient public namespace to expose default values to users.
- class gt4py.eve.datamodels.core.DataModel[source]
Bases:
object
Base class to automatically convert any subclass into a Data Model.
Inheriting from this class is equivalent to apply the
datamodel()
decorator to a class, except that theslots
option is alwaysFalse
(since it generates a new class) and all descendants will be also converted automatically in Data Models with the same options of the parent class (which does not happen when explicitly applying the decorator).See
datamodel()
for the description of the parameters.
- class gt4py.eve.datamodels.core.DataModelTP(*args, **kwargs)[source]
Bases:
gt4py.eve.datamodels.core._AttrsClassTP
,gt4py.eve.extended_typing.DevToolsPrettyPrintable
,Protocol
- gt4py.eve.datamodels.core.DefaultFieldTypeValidatorFactory()
Default type validator factory used by datamodels classes. None by default if running in optimized mode.
- class gt4py.eve.datamodels.core.ForwardRefValidator(factory: gt4py.eve.type_validation.TypeValidatorFactory, validator: typing.Union[gt4py.eve.type_validation.FixedTypeValidator, None, gt4py.eve.type_definitions.NothingType] = <class 'gt4py.eve.type_definitions.NOTHING'>)[source]
Bases:
object
Implementation of
attrs
field validator forForwardRef
typings.The first time is called it will update the class’ field type annotations and then create the actual type validator for the field.
- __call__(instance: gt4py.eve.datamodels.core.DataModel, attribute: attr._make.Attribute, value: typing_extensions.Any) None [source]
Call self as a function.
- factory: gt4py.eve.type_validation.TypeValidatorFactory
Type factory used to create the actual field validator.
- validator
Actual type validator created after resolving the forward references.
alias of
gt4py.eve.type_definitions.NOTHING
- class gt4py.eve.datamodels.core.FrozenModel[source]
Bases:
gt4py.eve.datamodels.core.DataModel
- classmethod update_forward_refs(localns: Optional[dict[str, typing_extensions.Any]] = None) type[_DataModelT]
Update Data Model class meta-information replacing forwarded type annotations with actual types.
- Parameters
localns – locals
dict
used in the evaluation of the annotations (globals are automatically taken frommodel.__module__
).- Returns
The provided class (so it can be used as a decorator too).
- class gt4py.eve.datamodels.core.GenericDataModel[source]
Bases:
gt4py.eve.datamodels.core.DataModel
- classmethod update_forward_refs(localns: Optional[dict[str, typing_extensions.Any]] = None) type[_DataModelT]
Update Data Model class meta-information replacing forwarded type annotations with actual types.
- Parameters
localns – locals
dict
used in the evaluation of the annotations (globals are automatically taken frommodel.__module__
).- Returns
The provided class (so it can be used as a decorator too).
- gt4py.eve.datamodels.core.Unchecked
Type hint marker to define fields that should NOT be type-checked at initialization.
alias of
gt4py.eve.datamodels.core._T
[gt4py.eve.datamodels.core._T
]
- class gt4py.eve.datamodels.core.ValidatorAdapter(validator: gt4py.eve.type_validation.FixedTypeValidator, description: str)[source]
Bases:
object
Adapter to use :class:`eve.type_validation.FixedTypeValidator`s as field validators.
- __call__(_instance: gt4py.eve.datamodels.core.DataModel, _attribute: attr._make.Attribute, value: typing_extensions.Any) None [source]
Call self as a function.
- gt4py.eve.datamodels.core._make_datamodel(cls: Type[_T], *, repr: bool, eq: bool, order: bool, unsafe_hash: bool, frozen: bool | Literal['strict'], match_args: bool, kw_only: bool, slots: bool, coerce: bool, generic: bool | Literal['True_no_checks'], type_validation_factory: Optional[FieldTypeValidatorFactory], _stacklevel_offset: int = 0) Type[_T] [source]
Actual implementation of the Data Model creation.
See
datamodel()
for the description of the parameters.
- gt4py.eve.datamodels.core.asdict(instance: gt4py.eve.datamodels.core.DataModel, *, value_serializer: Optional[collections.abc.Callable[[type[gt4py.eve.datamodels.core.DataModel], attr._make.Attribute, typing_extensions.Any], typing_extensions.Any]] = None) dict[str, typing_extensions.Any] [source]
Return the contents of a Data Model instance as a new mapping from field names to values.
- Parameters
instance – Data Model instance.
- Keyword Arguments
value_serializer – A hook that is called for every attribute or dict key/value and must return the (updated) value.
Examples
>>> @datamodel ... class C: ... x: int ... y: int >>> c = C(x=1, y=2) >>> assert asdict(c) == {'x': 1, 'y': 2}
- gt4py.eve.datamodels.core.astuple(instance: gt4py.eve.datamodels.core.DataModel) tuple[typing_extensions.Any, ...] [source]
Return the contents of a Data Model instance as a new tuple of field values.
- Parameters
instance – Data Model instance.
Examples
>>> @datamodel ... class C: ... x: int ... y: int >>> c = C(x=1, y=2) >>> assert astuple(c) == (1, 2)
- gt4py.eve.datamodels.core.coerced_field(*, default: Any = <class 'gt4py.eve.type_definitions.NOTHING'>, default_factory: Optional[Callable[[], Any]] = None, init: bool = True, repr: bool = True, hash: Optional[bool] = None, compare: bool = True, metadata: Optional[Mapping[Any, Any]] = None, kw_only: bool = False, converter: Callable[[Any], Any] | Literal['coerce'] | None = 'coerce', validator: AttrsValidator | FieldValidator | Sequence[AttrsValidator | FieldValidator] | None = None) Any
Field definition function using
converter="coerce"
.
- gt4py.eve.datamodels.core.concretize(datamodel_cls: type[GenericDataModelT], /, *type_args: type, class_name: Optional[str] = None, module: Optional[str] = None, support_pickling: bool = True, overwrite_definition: bool = True) type[DataModelT] [source]
Generate a new concrete subclass of a generic Data Model.
- Parameters
datamodel_cls – Generic Data Model to be subclassed.
type_args – Type definitions replacing the TypeVars in
datamodel_cls.__parameters__
.
- Keyword Arguments
class_name – Name of the new concrete class. The default value is the same of the generic Data Model replacing the TypeVars by the provided type_args in the name.
module – Value of the
__module__
attribute of the new class. The default value is the name of the module containing the generic Data Model.support_pickling – If
True
, support for pickling will be added by actually inserting the new class into the target module.overwrite_definition – If
True
, a previous definition of the class in the target module will be overwritten.
- gt4py.eve.datamodels.core.datamodel(cls: Optional[Type[_T]] = None, /, *, repr: bool = True, eq: bool = True, order: bool = False, unsafe_hash: bool = False, frozen: bool | Literal['strict'] = False, match_args: bool = True, kw_only: bool = False, slots: bool = False, coerce: bool = False, generic: bool = False, type_validation_factory: Optional[FieldTypeValidatorFactory] = <function field_type_validator_factory.<locals>._field_type_validator_factory>) Union[Type[_T], Callable[[Type[_T]], Type[_T]]] [source]
Add generated special methods to classes according to the specified attributes (class decorator).
It converts the class to an attrs with some extra features. Adding strict type validation functions for the fields is done by means of the
type_validation_factory
argument, falling back to the default factory(
DefaultFieldTypeValidatorFactory
). The generated field typevalidators are generated by using PEP 526
__annotations__
to determine field types and creating validation functions for them.- Parameters
cls – Original class definition.
- Keyword Arguments
repr – If
True
(default), a__repr__()
method will be generated if it does not overwrite a custom implementation defined in this class (not inherited).eq – If
True
(default),__eq__()
and__ne__()
methods will be generated if they do not overwrite custom implementations defined in this class (not inherited). The generated method compares the class as if it were a tuple of its fields, but both instances in the comparison must be of identical type.order – If
True
(default isFalse
), add__lt__()
,__le__()
,__gt__()
, and__ge__()
methods that behave like eq above and allow instances to be ordered. IfNone
mirror value of eq.unsafe_hash – If
False
, a__hash__()
method is generated in a safe way according to howeq
andfrozen
are set, or set toNone
(disabled) otherwise. IfTrue
, a__hash__()
method is generated anyway (use with care). Seedataclasses.dataclass()
for the complete explanation (or other sources like: https://hynek.me/articles/hashes-and-equality/).frozen – If
True
(default isFalse
), assigning to fields will generate an exception. This emulates read-only frozen instances. The__setattr__()
and__delattr__()
methods should not be defined in the class.match_args – If
True
(default) and__match_args__
is not already defined in the class, set__match_args__
on the class to support PEP 634 (Structural Pattern Matching). It is a tuple of all positional-only__init__
parameter names on Python 3.10 and later. Ignored on older Python versions.kw_only – If
True
(default isFalse
), make all fields keyword-only in the generated__init__
(ifinit
isFalse
, this parameter is ignored).slots – slots: If
True
(the default isFalse
),__slots__
attribute will be generated and a new slotted class will be returned instead of the original one.coerce – If
True
(default isFalse
), an automatic type converter will be generated for all fields.generic – If
True
(default isFalse
) the class should be aGeneric[]
class, and the generated Data Model will support creation of new Data Model subclasses when using concrete types as arguments ofDataModelClass[some_concret_type]
.type_validation_factory – Type validation factory used to build the field type validators. If
None
, type validators will not be generators.
- gt4py.eve.datamodels.core.evolve(inst, **changes)[source]
Create a new instance, based on inst with changes applied.
- gt4py.eve.datamodels.core.field(*, default: Any = <class 'gt4py.eve.type_definitions.NOTHING'>, default_factory: Optional[Callable[[], Any]] = None, init: bool = True, repr: bool = True, hash: Optional[bool] = None, compare: bool = True, metadata: Optional[Mapping[Any, Any]] = None, kw_only: bool = False, converter: Callable[[Any], Any] | Literal['coerce'] | None = None, validator: AttrsValidator | FieldValidator | Sequence[AttrsValidator | FieldValidator] | None = None) Any [source]
Define a new attribute on a class with advanced options.
- Keyword Arguments
default – If provided, this will be the default value for this field. This is needed because the
field()
call itself replaces the normal position of the default value.default_factory – If provided, it must be a zero-argument callable that will be called when a default value is needed for this field. Among other purposes, this can be used to specify fields with mutable default values. It is an error to specify both default and default_factory.
init – If
True
(default), this field is included as a parameter to the generated__init__()
method.repr – If
True
(default), this field is included in the string returned by the generated__repr__()
method.hash – This can be a
bool
orNone
(default). IfTrue
, this field is included in the generated__hash__()
method. IfNone
, use the value of compare, which would normally be the expected behavior: a field should be considered in the hash if it is used for comparisons. Setting this value to anything other thanNone
is discouraged.compare – If
True
(default), this field is included in the generated equality and comparison methods (__eq__(), __gt__(), et al.).metadata – An arbitrary mapping, not used at all by Data Models, and provided only as a third-party extension mechanism. Multiple third-parties can each have their own key, to use as a namespace in the metadata.
kw_only – If
True
(default isFalse
), make this field keyword-only in the generated__init__
(ifinit
isFalse
, this parameter is ignored).converter – Callable that is automatically called to convert attribute’s value. It is given the passed-in value, and the returned value will be used as the new value of the attribute before being passed to the validator, if any. If
"coerce"
is passed, a naive coercer converter will be generated. The automatic converter basically calls the constructor of the type indicated in the type hint, so it is assumed that new instances of this type can be created liketype_name(value)
. For collection types, there is not attempt to convert its items, only the collection type.validator – FieldValidator or list of FieldValidators to be used with this field. (Note that validators can also be set using decorator notation).
Examples
>>> from typing import List >>> @datamodel ... class C: ... mylist: List[int] = field(default_factory=lambda : [1, 2, 3]) >>> c = C() >>> c.mylist [1, 2, 3]
- gt4py.eve.datamodels.core.field_type_validator_factory()[source]
Create a factory of field type validators from a factory of regular type validators.
- gt4py.eve.datamodels.core.fields(model: Union[gt4py.eve.datamodels.core.DataModel, type[gt4py.eve.datamodels.core.DataModel]]) gt4py.eve.utils.FrozenNamespace
Return the field meta-information of a Data Model.
- Parameters
model – A Data Model class or instance.
Examples
>>> from typing import List >>> @datamodel ... class Model: ... name: str ... amount: int = 1 ... numbers: List[float] = field(default_factory=list) >>> fields(Model) FrozenNamespace(...name=Attribute(name='name', default=NOTHING, ...
- gt4py.eve.datamodels.core.frozen_model(cls: Optional[Type[_T]] = None, /, *, repr: bool = True, eq: bool = True, order: bool = False, unsafe_hash: bool = False, frozen: bool | Literal['strict'] = True, match_args: bool = True, kw_only: bool = False, slots: bool = False, coerce: bool = False, generic: bool = False, type_validation_factory: Optional[FieldTypeValidatorFactory] = <function field_type_validator_factory.<locals>._field_type_validator_factory>) Union[Type[_T], Callable[[Type[_T]], Type[_T]]]
Add generated special methods to classes according to the specified attributes (class decorator).
It converts the class to an attrs with some extra features. Adding strict type validation functions for the fields is done by means of the
type_validation_factory
argument, falling back to the default factory(
DefaultFieldTypeValidatorFactory
). The generated field typevalidators are generated by using PEP 526
__annotations__
to determine field types and creating validation functions for them.- Parameters
cls – Original class definition.
- Keyword Arguments
repr – If
True
(default), a__repr__()
method will be generated if it does not overwrite a custom implementation defined in this class (not inherited).eq – If
True
(default),__eq__()
and__ne__()
methods will be generated if they do not overwrite custom implementations defined in this class (not inherited). The generated method compares the class as if it were a tuple of its fields, but both instances in the comparison must be of identical type.order – If
True
(default isFalse
), add__lt__()
,__le__()
,__gt__()
, and__ge__()
methods that behave like eq above and allow instances to be ordered. IfNone
mirror value of eq.unsafe_hash –
If
False
, a__hash__()
method is generated in a safe way according to howeq
andfrozen
are set, or set toNone
(disabled) otherwise. IfTrue
, a__hash__()
method is generated anyway (use with care). Seedataclasses.dataclass()
for the complete explanation (or other sources like: https://hynek.me/articles/hashes-and-equality/).frozen – If
True
(default isFalse
), assigning to fields will generate an exception. This emulates read-only frozen instances. The__setattr__()
and__delattr__()
methods should not be defined in the class.match_args – If
True
(default) and__match_args__
is not already defined in the class, set__match_args__
on the class to support PEP 634 (Structural Pattern Matching). It is a tuple of all positional-only__init__
parameter names on Python 3.10 and later. Ignored on older Python versions.kw_only – If
True
(default isFalse
), make all fields keyword-only in the generated__init__
(ifinit
isFalse
, this parameter is ignored).slots – slots: If
True
(the default isFalse
),__slots__
attribute will be generated and a new slotted class will be returned instead of the original one.coerce – If
True
(default isFalse
), an automatic type converter will be generated for all fields.generic – If
True
(default isFalse
) the class should be aGeneric[]
class, and the generated Data Model will support creation of new Data Model subclasses when using concrete types as arguments ofDataModelClass[some_concret_type]
.type_validation_factory – Type validation factory used to build the field type validators. If
None
, type validators will not be generators.
- gt4py.eve.datamodels.core.frozenmodel(cls: Optional[Type[_T]] = None, /, *, repr: bool = True, eq: bool = True, order: bool = False, unsafe_hash: bool = False, frozen: bool | Literal['strict'] = True, match_args: bool = True, kw_only: bool = False, slots: bool = False, coerce: bool = False, generic: bool = False, type_validation_factory: Optional[FieldTypeValidatorFactory] = <function field_type_validator_factory.<locals>._field_type_validator_factory>) Union[Type[_T], Callable[[Type[_T]], Type[_T]]]
Data Model definition function using
frozen=True
.
- gt4py.eve.datamodels.core.get_fields(model: Union[gt4py.eve.datamodels.core.DataModel, type[gt4py.eve.datamodels.core.DataModel]]) gt4py.eve.utils.FrozenNamespace [source]
Return the field meta-information of a Data Model.
- Parameters
model – A Data Model class or instance.
Examples
>>> from typing import List >>> @datamodel ... class Model: ... name: str ... amount: int = 1 ... numbers: List[float] = field(default_factory=list) >>> fields(Model) FrozenNamespace(...name=Attribute(name='name', default=NOTHING, ...
- gt4py.eve.datamodels.core.is_datamodel(obj: typing_extensions.Any) bool [source]
Return True if obj is a Data Model class or an instance of a Data Model.
- gt4py.eve.datamodels.core.is_generic_datamodel_class(cls: type) bool [source]
Return
True
if obj is a generic Data Model class with type parameters.
- gt4py.eve.datamodels.core.root_validator(cls_method: gt4py.eve.datamodels.core._RV, /) gt4py.eve.datamodels.core._RV [source]
Define a custom root validator (decorator function).
The decorated functions should have the following signature:
def _root_validator_function(cls, instance):
wherecls
will be the class of the model andinstance
the actual instance being validated.
- gt4py.eve.datamodels.core.simple_type_validator_factory()
Field type validator for datamodels, supporting forward references.
- gt4py.eve.datamodels.core.update_forward_refs(model_cls: type[_DataModelT], localns: Optional[dict[str, typing_extensions.Any]] = None) type[_DataModelT] [source]
Update Data Model class meta-information replacing forwarded type annotations with actual types.
- Parameters
localns – locals
dict
used in the evaluation of the annotations (globals are automatically taken frommodel.__module__
).- Returns
The provided class (so it can be used as a decorator too).
- gt4py.eve.datamodels.core.validate(inst)[source]
Validate all attributes on inst that have a validator.
- gt4py.eve.datamodels.core.validator(name: str) collections.abc.Callable[[collections.abc.Callable[[gt4py.eve.datamodels.core._DM, attr._make.Attribute, gt4py.eve.datamodels.core._T], None]], collections.abc.Callable[[gt4py.eve.datamodels.core._DM, attr._make.Attribute, gt4py.eve.datamodels.core._T], None]] [source]
Define a custom field validator for a specific field (decorator function).
- Parameters
name – Name of the field to be validated by the decorated function.
The decorated functions should have the following signature:
def _validator_function(self, attribute, value):
whereself
will be the model instance being validated,attribute
the definition information of the attribute (the value of__datamodel_fields__.field_name
) andvalue
the actual value received for this field.
gt4py.eve.datamodels.validators module
Data Model field validators.
Check eve.datamodels
and attrs validation reference <https://www.attrs.org/en/stable/api.html#validators >
for additional information.
Note that validators are implemented as callable classes just to be able to
customize their __repr__
method.
- gt4py.eve.datamodels.validators.and_(*validators)[source]
A validator that composes multiple validators into one.
When called on a value, it runs all wrapped validators.
- Parameters
validators (callables) – Arbitrary number of validators.
New in version 17.1.0.
- gt4py.eve.datamodels.validators.deep_iterable(member_validator, iterable_validator=None)[source]
A validator that performs deep validation of an iterable.
- Parameters
member_validator – Validator(s) to apply to iterable members
iterable_validator – Validator to apply to iterable itself (optional)
New in version 19.1.0.
- Raises
TypeError – if any sub-validators fail
- gt4py.eve.datamodels.validators.deep_mapping(key_validator, value_validator, mapping_validator=None)[source]
A validator that performs deep validation of a dictionary.
- Parameters
key_validator – Validator to apply to dictionary keys
value_validator – Validator to apply to dictionary values
mapping_validator – Validator to apply to top-level mapping attribute (optional)
New in version 19.1.0.
- Raises
TypeError – if any sub-validators fail
- gt4py.eve.datamodels.validators.ge(val)[source]
A validator that raises ValueError if the initializer is called with a number smaller than val.
- Parameters
val – Inclusive lower bound for values
New in version 21.3.0.
- gt4py.eve.datamodels.validators.gt(val)[source]
A validator that raises ValueError if the initializer is called with a number smaller or equal to val.
- Parameters
val – Exclusive lower bound for values
New in version 21.3.0.
- gt4py.eve.datamodels.validators.in_(options)[source]
A validator that raises a ValueError if the initializer is called with a value that does not belong in the options provided. The check is performed using
value in options
.- Parameters
options (list, tuple, enum.Enum, …) – Allowed options.
- Raises
ValueError – With a human readable error message, the attribute (of type attrs.Attribute), the expected options, and the value it got.
New in version 17.1.0.
Changed in version 22.1.0: The ValueError was incomplete until now and only contained the human readable error message. Now it contains all the information that has been promised since 17.1.0.
- gt4py.eve.datamodels.validators.instance_of(type)[source]
A validator that raises a TypeError if the initializer is called with a wrong type for this particular attribute (checks are performed using isinstance therefore it’s also valid to pass a tuple of types).
- gt4py.eve.datamodels.validators.is_callable()[source]
A validator that raises a attr.exceptions.NotCallableError if the initializer is called with a value for this particular attribute that is not callable.
New in version 19.1.0.
- Raises
attr.exceptions.NotCallableError – With a human readable error message containing the attribute (attrs.Attribute) name, and the value it got.
- gt4py.eve.datamodels.validators.le(val)[source]
A validator that raises ValueError if the initializer is called with a number greater than val.
- Parameters
val – Inclusive upper bound for values
New in version 21.3.0.
- gt4py.eve.datamodels.validators.lt(val)[source]
A validator that raises ValueError if the initializer is called with a number larger or equal to val.
- Parameters
val – Exclusive upper bound for values
New in version 21.3.0.
- gt4py.eve.datamodels.validators.matches_re(regex, flags=0, func=None)[source]
A validator that raises ValueError if the initializer is called with a string that doesn’t match regex.
- Parameters
regex – a regex string or precompiled pattern to match against
flags (int) – flags that will be passed to the underlying re function (default 0)
func (callable) – which underlying re function to call. Valid options are re.fullmatch, re.search, and re.match; the default
None
means re.fullmatch. For performance reasons, the pattern is always precompiled using re.compile.
New in version 19.2.0.
Changed in version 21.3.0: regex can be a pre-compiled pattern.
- gt4py.eve.datamodels.validators.max_len(length)[source]
A validator that raises ValueError if the initializer is called with a string or iterable that is longer than length.
- Parameters
length (int) – Maximum length of the string or iterable
New in version 21.3.0.
- gt4py.eve.datamodels.validators.non_empty() FieldValidator [source]
Create a validator for non-empty iterables.
- gt4py.eve.datamodels.validators.optional(validator)[source]
A validator that makes an attribute optional. An optional attribute is one which can be set to
None
in addition to satisfying the requirements of the sub-validator.- Parameters
validator (callable or list of callables.) – A validator (or a list of validators) that is used for non-
None
values.
New in version 15.1.0.
Changed in version 17.1.0: validator can be a list of validators.
Module contents
Data Model classes and related utils and validators.
Data Models can be considered as enhanced attrs
/ dataclasses providing
additional features like automatic run-time type validation. Values assigned to fields
at initialization can be validated with automatic type checkings using the
field type definition. Custom field validation methods can also be added with
the validator()
decorator, and global instance validation methods with
root_validator()
.
The datamodels API tries to follow dataclasses
API conventions when possible,
but it is not an exact copy. Implementation-wise, Data Model classes are just
customized attrs
classes, and therefore external tools compatible with attrs
classes should also work with Data Models classes.
A valid __init__
method for the Data Model class is always generated. If the class
already defines a custom __init__
method, the generated method will be named
__auto_init__
and should be called from the custom __init__
to profit from
datamodels features. Additionally, if custom __pre_init__(self) -> None
or
__post_init__(self) -> None
methods exist in the class, they will be automatically
called from the generated __init__
before and after the instance creation.
The order of execution of the different components at initialization is the following:
__init__()
.
If a custom
__init__
already exists in the class, it will not be overwritten. It is your responsability to call__auto_init__
from there to obtain the described behavior.If there is not custom
__init__
, the one generated by datamodels will be called first.
__pre_init__()
, if it exists.For each field, in the order it was defined:
default factory (if any).
converter (if any).
all field validators.
root validators following the reversed class MRO order.
__post_init__()
, if it exists.
Examples
>>> @datamodel
... class SampleModel:
... name: str
... amount: int
...
... @validator('name')
... def _name_validator(self, attribute, value):
... if len(value) < 3:
... raise ValueError(
... f"Provided value '{value}' for '{attribute.name}' field is too short."
... )
>>> SampleModel("Some Name", 10)
SampleModel(name='Some Name', amount=10)
>>> SampleModel("A", 10)
Traceback (most recent call last):
...
ValueError: Provided value 'A' for 'name' field is too short.
>>> class AnotherSampleModel(DataModel):
... name: str
... friends: List[str]
...
... @root_validator
... def _root_validator(cls, instance):
... if instance.name in instance.friends:
... raise ValueError("'name' value cannot appear in 'friends' list.")
>>> AnotherSampleModel("Eve", ["Liam", "John"])
AnotherSampleModel(name='Eve', friends=['Liam', 'John'])
>>> AnotherSampleModel("Eve", ["Eve", "John"])
Traceback (most recent call last):
...
ValueError: 'name' value cannot appear in 'friends' list.
>>> @datamodel
... class CustomModel:
... value: float
... num_instances: ClassVar[int] = 0
...
... def __init__(self, a: int, b: int) -> None:
... self.__auto_init__(a/b)
...
... def __pre_init__(self) -> None:
... self.__class__.num_instances += 1
...
... def __post_init__(self) -> None:
... print(f"Instance {self.num_instances} == {self.value}")
>>> CustomModel(3, 2)
Instance 1 == 1.5
CustomModel(value=1.5)