-
Notifications
You must be signed in to change notification settings - Fork 49
Support optionally_keyed_by("foo", dict, use_msgspec=True)
#918
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
Open
ahal
wants to merge
4
commits into
taskcluster:main
Choose a base branch
from
ahal:ahal/push-wqqyrtqxppyt
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
1e86cd4
test: refactor test_util_schema tests to call Schema.validate
ahal 7c52c39
test: add test for optionally_keyed_by with dict
ahal 1b24dc3
refactor: stop returning value in Schema.validate
ahal 89dc1cc
fix: support optionally_keyed_by with underlying dict
ahal File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,7 +7,7 @@ | |
| import threading | ||
| from collections.abc import Mapping | ||
| from functools import reduce | ||
| from typing import Any, Literal, Optional, Union | ||
| from typing import Annotated, Any, Literal, Optional, Union, get_args, get_origin | ||
|
|
||
| import msgspec | ||
| import voluptuous | ||
|
|
@@ -70,11 +70,39 @@ def validate_schema(schema, obj, msg_prefix): | |
| raise Exception(f"{msg_prefix}\n{str(exc)}\n{pprint.pformat(obj)}") | ||
|
|
||
|
|
||
| def UnionTypes(*types): | ||
| """Use `functools.reduce` to simulate `Union[*allowed_types]` on older | ||
| Python versions. | ||
| """ | ||
| return reduce(lambda a, b: Union[a, b], types) | ||
| class OptionallyKeyedBy: | ||
| """Metadata class for optionally_keyed_by fields in msgspec schemas.""" | ||
|
|
||
| def __init__(self, *fields, wrapped_type): | ||
| self.fields = fields | ||
| self.wrapped_type = wrapped_type | ||
|
|
||
| @classmethod | ||
| def uses_keyed_by(cls, obj) -> bool: | ||
| if not isinstance(obj, dict) or len(obj) != 1: | ||
| return False | ||
|
|
||
| key = list(obj)[0] | ||
| if not key.startswith("by-"): | ||
| return False | ||
|
|
||
| return True | ||
|
|
||
| def validate(self, obj) -> None: | ||
| if not self.uses_keyed_by(obj): | ||
| # Not using keyed by, validate directly against wrapped type | ||
| msgspec.convert(obj, self.wrapped_type) | ||
| return | ||
|
|
||
| # First validate the outer keyed-by dict | ||
| bykeys = UnionTypes(*[Literal[f"by-{field}"] for field in self.fields]) | ||
| msgspec.convert(obj, dict[bykeys, dict]) | ||
|
|
||
| # Next validate each inner value. We call self.validate recursively to | ||
| # support nested `by-*` keys. | ||
| keyed_by_dict = list(obj.values())[0] | ||
| for value in keyed_by_dict.values(): | ||
| self.validate(value) | ||
|
|
||
|
|
||
| def optionally_keyed_by(*arguments, use_msgspec=False): | ||
|
|
@@ -86,13 +114,15 @@ def optionally_keyed_by(*arguments, use_msgspec=False): | |
| use_msgspec: If True, return msgspec type hints; if False, return voluptuous validator | ||
| """ | ||
| if use_msgspec: | ||
| # msgspec implementation - return type hints | ||
| # msgspec implementation - use Annotated[Any, OptionallyKeyedBy] | ||
| _type = arguments[-1] | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. drive-by-nit: might want to make this not raise |
||
| if _type is object: | ||
| return object | ||
| fields = arguments[:-1] | ||
| bykeys = [Literal[f"by-{field}"] for field in fields] | ||
| return Union[_type, dict[UnionTypes(*bykeys), dict[str, Any]]] | ||
| wrapper = OptionallyKeyedBy(*fields, wrapped_type=_type) | ||
| # Annotating Any allows msgspec to accept any value without validation. | ||
| # The actual validation then happens in Schema.__post_init__ | ||
| return Annotated[Any, wrapper] | ||
| else: | ||
| # voluptuous implementation - return validator function | ||
| schema = arguments[-1] | ||
|
|
@@ -291,6 +321,13 @@ def __getitem__(self, item): | |
| return self.schema[item] # type: ignore | ||
|
|
||
|
|
||
| def UnionTypes(*types): | ||
| """Use `functools.reduce` to simulate `Union[*allowed_types]` on older | ||
| Python versions. | ||
| """ | ||
| return reduce(lambda a, b: Union[a, b], types) | ||
|
|
||
|
|
||
| class Schema( | ||
| msgspec.Struct, | ||
| kw_only=True, | ||
|
|
@@ -318,14 +355,39 @@ class MySchema(Schema, forbid_unknown_fields=False, kw_only=True): | |
| foo: str | ||
| """ | ||
|
|
||
| def __post_init__(self): | ||
| if taskgraph.fast: | ||
| return | ||
|
|
||
| # Validate fields that use optionally_keyed_by. We need to validate this | ||
| # manually because msgspec doesn't support union types with multiple | ||
| # dicts. Any fields that use `optionally_keyed_by("foo", dict)` would | ||
| # otherwise raise an exception. | ||
| for field_name, field_type in self.__class__.__annotations__.items(): | ||
| origin = get_origin(field_type) | ||
| args = get_args(field_type) | ||
|
|
||
| if ( | ||
| origin is not Annotated | ||
| or len(args) < 2 | ||
| or not isinstance(args[1], OptionallyKeyedBy) | ||
| ): | ||
| # Not using `optionally_keyed_by` | ||
| continue | ||
|
|
||
| keyed_by = args[1] | ||
| obj = getattr(self, field_name) | ||
|
|
||
| keyed_by.validate(obj) | ||
|
|
||
| @classmethod | ||
| def validate(cls, data): | ||
| """Validate data against this schema.""" | ||
| if taskgraph.fast: | ||
| return data | ||
|
|
||
| try: | ||
| return msgspec.convert(data, cls) | ||
| msgspec.convert(data, cls) | ||
| except (msgspec.ValidationError, msgspec.DecodeError) as e: | ||
| raise msgspec.ValidationError(str(e)) | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider making this not a classmethod and checking that
key[3:] in self.fields