maite.utils.validation.check_one_of#

maite.utils.validation.check_one_of(name, arg, collection, *vals, requires_identity=False)[source]#

Check that arg is a member of collection or of vals.

Parameters:
namestr

The argument’s name.

argT (Any)

The argument.

collectionCollection | type[Enum]

Any collection (i.e., supports __contains__ and __iter__) or enum type.

*valsAny

Additional values to check arg against.

requires_identitybool, optional (default=False)

If True, all (non hash-based) membership checks are performed element-wise using x is e rather than the default x is e or x == e.

This can be helpful for ensuring strict identity, e.g., preventing 1 from matching against True.

Returns:
T

The input value, arg, unchanged.

Raises:
InvalidArgument

arg is not of a member of collections nor vals.

Unsatisfiable

An internal assertion error when the provided collection is empty.

Examples

>>> from maite.utils.validation import check_one_of
>>> try:
...     check_one_of("foo", None, [1, 2])
... except:
...     print("maite.errors.InvalidArgument: Expected `foo` to be one of: 1, 2. Got `None`.")
maite.errors.InvalidArgument: Expected `foo` to be one of: 1, 2. Got `None`.

Including None as an acceptable value

>>> print(check_one_of("foo", None, [1, 2], None))
None

Enforcing strict identity using requires_identity:

>>> check_one_of("foo", 1, [True])  # `1` == `True`
1
>>> try:
...     check_one_of("foo", 1, [True], requires_identity=True)
... except:
...     print("maite.errors.InvalidArgument: Expected `foo` to be: True. Got `1`.")
maite.errors.InvalidArgument: Expected `foo` to be: True. Got `1`.

Support for enums:

>>> from enum import Enum
>>> class Pet(Enum):
...     cat = 1
...     dog = 2
>>> try:
...     check_one_of("bar", 88, Pet)
... except:
...     print("maite.errors.InvalidArgument: Expected `bar` to be one of: Pet.cat, Pet.dog. Got `88`.")
maite.errors.InvalidArgument: Expected `bar` to be one of: Pet.cat, Pet.dog. Got `88`.
>>> check_one_of("bar", Pet.cat, Pet)
<Pet.cat: 1>