predictably.validate.check_sequence#
- predictably.validate.check_sequence(input_seq: Sequence[Any], sequence_type: type | Tuple[type, ...] | None = None, element_type: type | Tuple[type, ...] | None = None, coerce_output_type_to: type | None = None, coerce_scalar_input: bool = False, sequence_name: str | None = None) Sequence[Any][source]#
Check whether an object is a sequence with optional check of element types.
If element_type is supplied all elements are also checked against provided types.
- Parameters:
- input_seqAny
The input sequence to be validated.
- sequence_typetype or tuple[type], default=None
The allowed sequence type that seq can be an instance of.
- element_typetype or tuple[type], default=None
The allowed type(s) for elements of seq.
- coerce_output_type_tosequence type, default=None
The sequence type that the output sequence should be coerced to.
If None, then the output sequence is the same as input sequence.
If a sequence type (e.g., list, tuple) is provided then the output sequence is coerced to that type.
- coerce_scalar_inputbool, default=False
Whether scalar input should be coerced to a sequence type prior to running the check. If True, a scalar input like will be coerced to a tuple containing a single scalar. To output a sequence type other than a tuple, set the coerce_output_type_to keyword to the desired sequence type (e.g., list).
- sequence_namestr, default=None
Name of input_seq to use if error messages are raised.
- Returns:
- Sequence
The input sequence if has expected type.
- Raises:
- TypeError
If seq is not instance of sequence_type or
element_type is not Noneand all elements are not instances of element_type.
Examples
>>> from predictably._core._base import BaseEstimator, BaseObject >>> from predictably.validate import is_sequence
>>> check_sequence([1, 2, 3]) [1, 2, 3]
Generators are not sequences so an error is raised
>>> check_sequence((c for c in [1, 2, 3]))
The check can require a certain type of sequence
>>> check_sequence([1, 2, 3, 4], sequence_type=list) [1, 2, 3, 4]
Expected to raise and error because the input is not a tuple
>>> check_sequence([1, 2, 3, 4], sequence_type=tuple)
It is also possible to check the type of sequence elements
>>> check_sequence([1, 2, 3], element_type=int) [1, 2, 3] >>> check_sequence([1, 2, 3, 4], sequence_type=list, element_type=(int, float)) [1, 2, 3, 4]
The check also works with BaseObjects
>>> check_sequence((BaseObject(), BaseEstimator()), element_type=BaseObject) (BaseObject(), BaseEstimator())