fairseq2.utils.validation¶
This module provides a set of helper types for object state validation. These types are primarly used by recipe and asset configuration dataclasses to ensure that all fields are set correctly.
A class -typically a configuration dataclass- that wants to support validation
should expose a validate(self) -> ValidationResult method. Optionally,
the class can derive from the runtime-checkable Validatable protocol
to make its intent more clear.
A typical implementation of a validate() method looks like the following:
from dataclasses import dataclass
from fairseq2.utils.validation import Validatable, ValidationResult
@dataclass
class FooConfig(Validatable):
field1: str
field2: int
def validate(self) -> ValidationResult:
result = ValidationResult()
if not self.field1:
result.add_error("`field1` must be a non-empty string.")
if self.field2 < 1:
result.add_error("`field2` must be a positive integer.")
return result
Note that FooConfig must NOT call validate() on its sub-fields that are
validatable. ObjectValidator will traverse the object graph and call
each validate() method it finds in dataclasses as well as in composite
objects of types list, Mapping, Set, and tuple.
Whenever FooConfig is used in a recipe configuration, fairseq2 will ensure
that it is validated before setting RecipeContext.config. To manually
validate an object outside of recipes, StandardObjectValidator can
be used:
from dataclasses import dataclass
from fairseq2.utils.validation import (
ObjectValidator,
StandardObjectValidator,
Validatable,
ValidationError,
ValidationResult,
)
@dataclass
class FooConfig(Validatable):
field1: str
field2: int
def validate(self) -> ValidationResult:
result = ValidationResult()
if not self.field1:
result.add_error("`field1` must be a non-empty string.")
if self.field2 < 1:
result.add_error("`field2` must be a positive integer.")
return result
config = FooConfig(field1="foo", field2=0)
validator: ObjectValidator = StandardObjectValidator()
try:
validator.validate(config)
except ValidationError as ex:
# Prints an error message indicating that `field2` must be a
# positive integer.
print(ex.result)
- class fairseq2.utils.validation.ObjectValidator[source]¶
Bases:
ABCValidates an object along with its sub-objects if it is a composite object (i.e. a
dataclass,list,Mapping,Set, ortuple) and raises aValidationErrorif any of them returns an error.- abstract validate(obj: object) None[source]¶
Validates
obj.- Raises:
ValidationError – If
objor one of its sub-objects has a validation error.
- final class fairseq2.utils.validation.StandardObjectValidator[source]¶
Bases:
ObjectValidatorRepresents the standard implementation of
ObjectValidator.- validate(obj: object) None[source]¶
Validates
obj.- Raises:
ValidationError – If
objor one of its sub-objects has a validation error.
- class fairseq2.utils.validation.Validatable(*args, **kwargs)[source]¶
Bases:
ProtocolRepresents the protocol for validatable objects.
- validate() ValidationResult[source]¶
Validates the state of the object.
- final class fairseq2.utils.validation.ValidationResult[source]¶
Bases:
objectHolds the result of a
validate()call.- add_sub_result(field: str, result: ValidationResult) None[source]¶
Adds the validation result of a sub-object as a sub-result.
fieldspecifies the name of the sub-object. For a dataclass, it is the name of the field, for aMapping, it is the name of the key formatted asf"[{repr(key)}]", for alist,Set, ortuple, it is the index of the value formatted asf"[{index}]".
- has_error() bool[source]¶
Returns
Trueif the object or any of its sub-objects have a validation error.
- property errors: Sequence[str]¶
Returns the validation errors of the object, excluding errors of its sub-objects.
- property sub_results: Mapping[str, ValidationResult]¶
Returns the validation results of the sub-objects.
- exception fairseq2.utils.validation.ValidationError(result: ValidationResult | str, *, field: str | None = None)[source]¶
Bases:
ExceptionRaised when a validation error occurs.
If
fieldis provided,resultwill be treated as the sub-result of the specified field.- result: ValidationResult¶