UnionAttribute

class dtaianomaly.type_validation.UnionAttribute(*attribute_validators: BaseAttributeValidation)[source]

Validate multiple BaseAttributeValidation objects.

Combine multiple BaseAttributeValidation using an OR-operation. This validator will check if a given value satisfies the rules of the BaseAttributeValidation. Multiple attribute validators can be either passed to the constructor, but it is also possible to combine them with | for a simpler and more pythonic syntax.

Parameters:
*attribute_validatorstwo or more BaseAttributeValidation objects

The attribute validators that are combined through an OR-operation for validation. The validators must be passes as separate parameters to the constructor. There should be at least two validators. If any of the given validators is a UnionAttribute, then the validators will be flattened to contain only a single list of validators.

Examples

>>> from dtaianomaly.type_validation import IntegerAttribute, NoneAttribute
>>> optional_int = IntegerAttribute(minimum=0) | NoneAttribute()
>>> # Equivalently: optional_int = UnionAttribute(IntegerAttribute(minimum=0), NoneAttribute())
>>> optional_int.raise_error_if_invalid(None, "my_attribute", "MyClass")  # No error
>>> optional_int.raise_error_if_invalid(42, "my_attribute", "MyClass")    # No error
>>> optional_int.raise_error_if_invalid("not-an-optional-int", "my_attribute", "MyClass")
Traceback (most recent call last):
    ...
TypeError: Attribute 'my_attribute' in class 'MyClass' must be of type int or None, but received 'not-an-optional-int' of type <class 'str'>!
>>> optional_int.raise_error_if_invalid(-5, "my_attribute", "MyClass")
Traceback (most recent call last):
    ...
ValueError: Attribute 'my_attribute' in class 'MyClass' must be greater than or equal to 0 or None, but received '-5'!
raise_error_if_invalid(value, name: str, class_name: str) None

Raise an error if the given value is invalid.

Check if the type and the exact value are permitted, according to the rules of this attribute validation. If either the type or the value is invalid, an error is raised accordingly. Otherwise, nothing happens.

Parameters:
valueany

The value to verify.

namestr

The name of the attribute that is being checked. Used for generating clear error messages, if needed.

class_namestr

The name of the class to which the attribute belongs. Used for generating clear error messages, if needed.

Raises:
TypeError

If the type of the given value is invalid according to the rules of this BaseAttributeValidation.

ValueError

If the value of the given value is invalid according to the rules of this BaseAttributeValidation.