validate_exactly_one_of#

safir.pydantic.validate_exactly_one_of(*settings)#

Generate a 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 validator. This is a validator generator that can produce a 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:

The validator.

Return type:

Callable

Examples

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

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

    _validate_options = validator("baz", always=True, allow_reuse=True)(
        validate_exactly_one_of("foo", "bar", "baz")
    )

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