Dynamic Enums #128
Unanswered
thomascobb
asked this question in
Q&A
Replies: 1 comment 2 replies
-
You can use the deserialized data during validation using validators. from dataclasses import dataclass, field
from apischema import ValidationError, deserialize, validator, serialize
@dataclass
class Data:
allowed: list[str]
values: list[str] = field()
@validator(values)
def check_values_are_allowed(self):
for index, value in enumerate(self.values):
if value not in self.allowed:
yield index, f"value not allowed, should be one of {self.allowed}"
assert deserialize(
Data, {"allowed": ["foo", "bar"], "values": ["foo", "bar", "foo"]}
) == Data(["foo", "bar"], ["foo", "bar", "foo"])
try:
deserialize(Data, {"allowed": ["foo"], "values": ["foo", "bar", "foo"]})
except ValidationError as err:
assert serialize(err) == [
{"loc": ["values", 1], "err": ["value not allowed, should be one of ['foo']"]}
] Moreover, when it comes to schema generation, it's possible to add a |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I would like to make a dynamic enum, where the values are based on the presence of keys in a document, something like json-schema-org/json-schema-spec#706.
I have read through the associated issues on json-schema-org, and they all seem to leave it up to the implementation as to whether/how this should be implemented:
I could do this outside apischema by post-processing the deserialized objects, but I wondered if this was within the scope of what apischema could do, and if you'd given it any thought?
Thanks,
Tom
Beta Was this translation helpful? Give feedback.
All reactions