Skip to content

bagof.validators.base

Base class for all validators.

Attributes

register_validator module-attribute

register_validator = Validator.register

Backward-compatible alias for Validator.register

get_validator module-attribute

get_validator = Validator.get

Backward-compatible alias for Validator.get

get_validator_class module-attribute

get_validator_class = Validator.get_class

Backward-compatible alias for Validator.get_class

Classes

Validator

Validator(hint: Any = UNSET, compose: bool = False)

Bases: MagicHint[T]

Base class for magic validators.

The default validator falls back to a rather crude heuristic to check whether the type of the validated object is compatible with the type hint.

Warning

This heuristic does not work well for generic types, so it is recommended to implement a custom validator for generic types.

Parameters:

Name Type Description Default
hint Any

The type hint to use for this magic object. If not provided, the default hint for the class is used.

UNSET
compose bool

Whether to compose this validator with others, when they are found in Annotated metadata.

False

Methods:

__call__
__call__(value: T) -> None

Validate the given value.

Parameters:

Name Type Description Default
value T

The value to validate.

required

Raises:

Type Description
ValidationError

If the value is not valid for this validator.

error
error(value: Any, message: str | None = None, **kwargs) -> ValidationError

Return a ValidationError with the given value and message.

type_error
type_error(value: Any, message: str | None = None) -> TypeValidationError

Return a TypeValidationError with the given value.

value_error
value_error(value: Any, message: str | None = None) -> ValueValidationError

Return a ValueValidationError with the given value.

register staticmethod
register(validator: Type[Validator], *hints: Unpack[tuple[Any]], registry: ValidatorRegistry = ...) -> Type[Validator]
register(*hints: Unpack[tuple[Any]], registry: ValidatorRegistry = ...) -> ClassDecorator

Decorator to register a validator class for one or more type hints.

Can be used as a bare decorator (its first argument is then the validator class itself, as in the example below), or called with one or more type hints to obtain a decorator factory instead.

Example

@Validator.register
class IntValidator(Validator[int]):

    DEFAULT = int

    def __call__(self, value: int) -> None:
        try:
            int(value)
        except (TypeError, ValueError) as e:
            raise self.type_error(value) from e

Parameters:

Name Type Description Default
*hints

One or more type hints to register the validator class for. Defaults to the validator class's DEFAULT hint if none are given. When used as a bare decorator, the first "hint" is actually the validator class to register.

()
registry ValidatorRegistry

The registry to register the validator class in. Defaults to the global registry.

VALIDATORS

Returns:

Type Description
Type[Validator] | ClassDecorator

When used as a bare decorator, the same validator class, now registered. Otherwise, a decorator that registers the validator class it is applied to.

get staticmethod
get(hint: Any, registry: ValidatorRegistry = VALIDATORS, fallback: Type[Validator] | None = UNSET) -> Validator | None

Get the best-matching conversion function for a given type hint.

The returned validator is a callable that returns None on success and raises a ValidationError on failure:

Example

>>> from bagof.validators import get_validator
>>> validate = get_validator(int)
>>> validate(3)
>>> validate("x")
TypeValidationError: IsNumber(<class 'int'>): Not a valid instance.
|> value = 'x'

Parameters:

Name Type Description Default
hint Any

The type hint for which to get a validator.

required
registry ValidatorRegistry

The registry to look up the validator in. Defaults to the global registry.

VALIDATORS
fallback Type[Validator] | None

The fallback validator class to use if no matching validator is found. Defaults to Validator. Pass None explicitly to get None instead of a fallback.

UNSET

Returns:

Type Description
Validator | None

The best-matching validator for the given type hint, or None if no matching validator is found and no fallback is provided.

get_class staticmethod
get_class(hint: Any, registry: ValidatorRegistry = VALIDATORS, fallback: Type[Validator] | None = UNSET) -> Type[Validator] | None

Get the best-matching conversion class for a given type hint.

Parameters:

Name Type Description Default
hint Any

The type hint for which to get a validator.

required
registry ValidatorRegistry

The registry to look up the validator in. Defaults to the global registry.

VALIDATORS
fallback Type[Validator] | None

The fallback validator class to use if no matching validator is found. Defaults to Validator. Pass None explicitly to get None instead of a fallback.

UNSET

Returns:

Type Description
Type[Validator] | None

The best-matching validator class for the given type hint, or None if no matching validator is found and no fallback is provided.