Skip to content

validators

validators

Pydantic-integrated field validators for parameter models.

Provides two validator types used as Annotated metadata on fields in config/ models:

  • DependsOnValidator -- enforces conditional dependencies between fields (e.g. order_training_examples_by requires group_training_examples_by).
  • ValueValidator -- applies an arbitrary predicate to the field value (e.g. "learning rate must be in (0, 1)").

Both implement __get_pydantic_core_schema__ so Pydantic runs them as after-validators during model construction.

Classes:

Name Description
DependsOnValidator

Conditional dependency validator for Pydantic fields.

ValueValidator

Predicate-based validator for field values.

Attributes:

Name Type Description
AutoParamRangeValidator

Pre-built ValueValidator that accepts "auto" or any non-negative number.

AutoParamRangeValidator = ValueValidator(lambda p: range_validator(p, lambda v: v >= 0)) module-attribute

Pre-built ValueValidator that accepts "auto" or any non-negative number.

DependsOnValidator(depends_on, depends_on_func, value_func) dataclass

Conditional dependency validator for Pydantic fields.

Rejects a field value when a related field does not satisfy a precondition. Attach via Annotated metadata on the dependent field.

Parameters:

Name Type Description Default
depends_on str

Name of the field that this field depends on.

required
depends_on_func Callable[[Any], bool]

Predicate applied to the dependency field's value. Must return True for the dependent field to be accepted.

required
value_func Callable[[Any], bool] | None

Optional predicate on the current field's own value. When None (or when it returns falsy), the dependency check is skipped and the value passes through unchanged.

required

Example::

order_training_examples_by: Annotated[
    str | None,
    DependsOnValidator(
        depends_on="group_training_examples_by",
        depends_on_func=lambda v: v is not None,
        value_func=lambda v: v is not None,
    ),
    Field(...),
] = None

Methods:

Name Description
validate

Run the dependency check during Pydantic validation.

validate(value, info)

Run the dependency check during Pydantic validation.

Parameters:

Name Type Description Default
value

The value being validated.

required
info ValidationInfo

Pydantic validation context containing sibling field data.

required

Returns:

Type Description

The validated value if all conditions pass.

Raises:

Type Description
ValueError

If the dependency field is absent from the model or its value does not satisfy depends_on_func.

Source code in src/nemo_safe_synthesizer/configurator/validators.py
def validate(self, value, info: ValidationInfo):
    """Run the dependency check during Pydantic validation.

    Args:
        value: The value being validated.
        info: Pydantic validation context containing sibling field data.

    Returns:
        The validated value if all conditions pass.

    Raises:
        ValueError: If the dependency field is absent from the model or
            its value does not satisfy ``depends_on_func``.
    """
    if self.depends_on not in info.data:
        raise ValueError(f"{info.field_name} is only allowed in model with {self.depends_on}")

    vf = self.value_func if self.value_func is not None else lambda x: x

    if vf(value):
        if self.depends_on_func(info.data.get(self.depends_on)):
            return value
        else:
            raise ValueError(
                f"{info.field_name} is only allowed when {self.depends_on} pass condition \
                `{inspect.getsource(self.depends_on_func)}`"
            )

    return value

ValueValidator(value_func) dataclass

Predicate-based validator for field values.

Wraps an arbitrary boolean function and raises ValueError when it returns False. Commonly used inline: ValueValidator(value_func=lambda v: v > 0).

Parameters:

Name Type Description Default
value_func Callable[[Any], bool]

Predicate applied to the field value. Returns True if valid.

required

Methods:

Name Description
validate

Apply value_func to the field value during Pydantic validation.

validate(value, info)

Apply value_func to the field value during Pydantic validation.

Parameters:

Name Type Description Default
value

The raw field value.

required
info ValidationInfo

Pydantic validation context.

required

Returns:

Type Description

The original value if the predicate passes.

Raises:

Type Description
ValueError

If the predicate returns False.

Source code in src/nemo_safe_synthesizer/configurator/validators.py
def validate(self, value, info: ValidationInfo):
    """Apply ``value_func`` to the field value during Pydantic validation.

    Args:
        value: The raw field value.
        info: Pydantic validation context.

    Returns:
        The original ``value`` if the predicate passes.

    Raises:
        ValueError: If the predicate returns ``False``.
    """
    logger.debug(f"Field {info.field_name}, value={value}, validating")
    if self.value_func(value):
        return value
    try:
        # Sometimes inspect.getsource() raises an OSError for lambda
        # functions defined inline, hence the try/except.
        src = inspect.getsource(self.value_func)
        msg = f"Field {info.field_name}, value={value}, did not pass validation: {src}"
    except OSError:
        msg = f"Field {info.field_name}, value={value}, did not pass validation"
    raise ValueError(msg)

range_validator(value, func)

Check a numeric value against func, passing "auto" sentinels unconditionally.

func is typically a predicate that asserts a numeric range (e.g. non-negative, within (0, 1)).

Parameters:

Name Type Description Default
value int | float

The value to validate -- may be a number or the string "auto".

required
func Callable

Predicate applied when value is numeric (e.g. lambda v: v >= 0).

required

Returns:

Type Description
bool

True if value is "auto" or func(value) is truthy.

Source code in src/nemo_safe_synthesizer/configurator/validators.py
def range_validator(value: int | float, func: Callable) -> bool:
    """Check a numeric value against ``func``, passing ``"auto"`` sentinels unconditionally.

    ``func`` is typically a predicate that asserts a numeric range (e.g.
    non-negative, within ``(0, 1)``).

    Args:
        value: The value to validate -- may be a number or the string ``"auto"``.
        func: Predicate applied when ``value`` is numeric (e.g. ``lambda v: v >= 0``).

    Returns:
        ``True`` if ``value`` is ``"auto"`` or ``func(value)`` is truthy.
    """
    return True if value == "auto" else func(value)