Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add basic Literal Validator #7009

Merged
merged 3 commits into from
Mar 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/changes/newsfragments/7009.new
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A new Validator ``LiteralValidator`` was added. This allows validating against the members of a ``typing.Literal``.
2 changes: 2 additions & 0 deletions src/qcodes/validators/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
Enum,
Ints,
Lists,
LiteralValidator,
Multiples,
MultiType,
MultiTypeAnd,
Expand All @@ -33,6 +34,7 @@
"Enum",
"Ints",
"Lists",
"LiteralValidator",
"MultiType",
"MultiTypeAnd",
"MultiTypeOr",
Expand Down
52 changes: 51 additions & 1 deletion src/qcodes/validators/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import typing
from collections import abc
from collections.abc import Hashable
from typing import Any, Generic, Literal, TypeVar, cast
from typing import Any, Generic, Literal, TypeVar, cast, get_args

Check warning on line 12 in src/qcodes/validators/validators.py

View check run for this annotation

Codecov / codecov/patch

src/qcodes/validators/validators.py#L12

Added line #L12 was not covered by tests

import numpy as np

Expand Down Expand Up @@ -500,6 +500,56 @@
return self._values.copy()


class LiteralValidator(Validator[T]):

Check warning on line 503 in src/qcodes/validators/validators.py

View check run for this annotation

Codecov / codecov/patch

src/qcodes/validators/validators.py#L503

Added line #L503 was not covered by tests
"""

A validator that allows users to check that values supplied are in set of members
of some typing.Literal.


.. code-block:: python

from typing import Literal

A123 = Literal[1,2,3]
A123Val = LiteralValidator[A123]
a123 = A123()

a123().validate(1) # pass

a123().validate(5) # fails
a123().validate("some_str") # fails

"""

def __init__(self) -> None:

Check warning on line 525 in src/qcodes/validators/validators.py

View check run for this annotation

Codecov / codecov/patch

src/qcodes/validators/validators.py#L525

Added line #L525 was not covered by tests
self._orig_class = getattr(self, "__orig_class__", None)

@property
def valid_values(self) -> tuple[Any, ...]:

Check warning on line 529 in src/qcodes/validators/validators.py

View check run for this annotation

Codecov / codecov/patch

src/qcodes/validators/validators.py#L528-L529

Added lines #L528 - L529 were not covered by tests
# self__orig_class__ is available when init is executed so
# looking up the concrete type of T has to be postponed to here
orig_class = getattr(self, "__orig_class__", None)

if orig_class is None:
raise TypeError(
"Cannot find valid literal members for Validator."
" Did you remember to instantiate as `LiteralValidator[SomeLiteralType]()"
)

valid_args = get_args(get_args(orig_class)[0])
return valid_args

def validate(self, value: T, context: str = "") -> None:

Check warning on line 543 in src/qcodes/validators/validators.py

View check run for this annotation

Codecov / codecov/patch

src/qcodes/validators/validators.py#L543

Added line #L543 was not covered by tests
if value not in self.valid_values:
raise ValueError(
f"{value} is not a member of {self.valid_values}; {context}"
)

def __repr__(self) -> str:

Check warning on line 549 in src/qcodes/validators/validators.py

View check run for this annotation

Codecov / codecov/patch

src/qcodes/validators/validators.py#L549

Added line #L549 was not covered by tests
return f"<Literal{list(self.valid_values)}>"


class OnOff(Validator[str]):
"""
Requires either the string 'on' or 'off'.
Expand Down
50 changes: 50 additions & 0 deletions tests/validators/test_literal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from typing import Literal

import pytest

from qcodes.validators.validators import LiteralValidator


def test_literal_validator() -> None:
A123 = Literal[1, 2, 3]

A123Val = LiteralValidator[A123]

a123_val = A123Val()

a123_val.validate(1)

with pytest.raises(ValueError, match="5 is not a member of "):
a123_val.validate(5, context="Outside range") # pyright: ignore[reportArgumentType]

with pytest.raises(ValueError, match="some_str is not a member of "):
a123_val.validate("some_str", context="Wrong type") # pyright: ignore[reportArgumentType]


def test_literal_validator_repr() -> None:
A123 = Literal[1, 2, 3]

A123Val = LiteralValidator[A123]

a123_val = A123Val()

assert repr(a123_val) == "<Literal[1, 2, 3]>"


def test_valid_values() -> None:
A123 = Literal[1, 2, 3]

A123Val = LiteralValidator[A123]

a123_val = A123Val()

assert a123_val.valid_values == (1, 2, 3)


def test_missing_generic_arg_raises_at_runtime():
wrong_validator = LiteralValidator()

with pytest.raises(
TypeError, match="Cannot find valid literal members for Validator"
):
wrong_validator.validate(1)
Loading