Restore init=False dataclass fields when converting from JSON - #1920
Open
Kayvan-Zahiri wants to merge 1 commit into
Open
Kayvan-Zahiri wants to merge 1 commit into
Kayvan-Zahiri wants to merge 1 commit into
Conversation
Co-authored-by: Cursor <cursoragent@cursor.com>
|
|
1 similar comment
|
|
This branch has not been deployed
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
A dataclass with a
field(init=False)can be encoded but not decoded. The JSON encoder includes every field, andvalue_to_typethen passes all of them to the constructor, which rejects the non-init ones:I hit this on 1.34.0 with
DataConverter.defaultround-tripping a plain dataclass like the one above.The fix keeps
init=Falsefields out of the constructor call. If the payload has a value for one, it's converted with the field's type hint like any other field and set after construction.object.__setattr__is used so frozen dataclasses work too. Without that last step a field set after__init__(like a counter) would silently reset to its default on decode.Added
test_json_dataclass_non_init_fields_round_tripintests/test_converter.py, covering a field computed in__post_init__, a field changed after construction, and a frozen dataclass. It fails onmainwith theTypeErrorabove and passes with the fix.Validation:
pytest tests/test_converter.py: 41 passedruff check,ruff format --check,basedpyrightandmypy --namespace-packages --check-untyped-defson the changed files: clean.pyrightis clean on_payload_converter.py. Ontests/test_converter.pyit only reportspytestas an unresolved import, which it also does onmainin my env.