validate_exactly_one_of#

safir.pydantic.validate_exactly_one_of(*settings)#

Generate a model validator imposing a one and only one constraint.

Sometimes, models have a set of attributes of which one and only one may be set. Ideally this is represented properly in the type system, but occasionally it’s more convenient to use a model validator. This is a model validator generator that can produce a model validator function that ensures one and only one of an arbitrary set of attributes must be set.

Parameters:

*settings (str) – List of names of attributes, of which one and only one must be set. At least two attribute names must be listed.

Returns:

Resulting model validator.

Return type:

Callable

Examples

Use this inside a Pydantic class as a model validator as follows:

class Foo(BaseModel):
    foo: Optional[str] = None
    bar: Optional[str] = None
    baz: Optional[str] = None

    _validate_options = model_validator(mode="after")(
        validate_exactly_one_of("foo", "bar", "baz")
    )

The attribute listed as the first argument to the model_validator call must be the last attribute in the model definition so that any other attributes have already been seen.