LiteralAttribute

class dtaianomaly.type_validation.LiteralAttribute(*values: str | list[str])[source]

Validator for literals.

Check wether a given value is a valid literal. A literal is a value of type string but must be one of the predefined values.

Parameters:
*valuesstring or list of string

The valid literals.

Examples

>>> from dtaianomaly.type_validation import LiteralAttribute
>>> a_literal = LiteralAttribute("one", "two", "three")
>>> a_literal.raise_error_if_invalid("one", "my_attribute", "MyClass")    # No error
>>> a_literal.raise_error_if_invalid("two", "my_attribute", "MyClass")    # No error
>>> a_literal.raise_error_if_invalid("three", "my_attribute", "MyClass")  # No error
>>> a_literal.raise_error_if_invalid(0, "my_attribute", "MyClass")
Traceback (most recent call last):
    ...
TypeError: Attribute 'my_attribute' in class 'MyClass' must be of type string, but received '0' of type <class 'int'>!
>>> a_literal.raise_error_if_invalid("four", "my_attribute", "MyClass")
Traceback (most recent call last):
    ...
ValueError: Attribute 'my_attribute' in class 'MyClass' must be in {'one', 'three', 'two'}, but received 'four'!
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.