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:
ABC
Validates an object along with its sub-objects if it is a composite object (i.e. a
dataclass
,list
,Mapping
,Set
, ortuple
) and raises aValidationError
if any of them returns an error.- abstract validate(obj: object) None [source]¶
Validates
obj
.- Raises:
ValidationError – If
obj
or one of its sub-objects has a validation error.
- final class fairseq2.utils.validation.StandardObjectValidator[source]¶
Bases:
ObjectValidator
Represents the standard implementation of
ObjectValidator
.- validate(obj: object) None [source]¶
Validates
obj
.- Raises:
ValidationError – If
obj
or one of its sub-objects has a validation error.
- class fairseq2.utils.validation.Validatable(*args, **kwargs)[source]¶
Bases:
Protocol
Represents the protocol for validatable objects.
- validate() ValidationResult [source]¶
Validates the state of the object.
- final class fairseq2.utils.validation.ValidationResult[source]¶
Bases:
object
Holds 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.
field
specifies 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
True
if 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:
Exception
Raised when a validation error occurs.
If
field
is provided,result
will be treated as the sub-result of the specified field.- result: ValidationResult¶