Repository navigation
Keep floats in int and float unions when decoding typed JSON payloads - #1958
Closed
LindseyZ1205 wants to merge 1 commit into
Closed
LindseyZ1205 wants to merge 1 commit into
LindseyZ1205 wants to merge 1 commit into
Conversation
value_to_type tries the members of a union in order, and the int conversion accepts a float and truncates it. So a float decoded with a type hint such as int | float became an int: 9.99 became 9, also in dataclass fields, lists and dict values. When the union has a float member and the value is a float, convert it as a float. A plain int hint still truncates, as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Contributor
|
Generally we would recommend using the |
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.
value_to_typetries the members of a union in order, and theintconversion accepts a float and truncates it. So with a type hint such asint | float, a float is decoded as an int:The same happens for
int | float | None,list[int | float]and dict values. When the union has afloatmember and the value is a float, convert it as a float before trying the other members. A plaininthint still truncates, asok(int, 5.5, 5)intest_json_type_hintsexpects, and an int value in anint | floatunion is still an int.I found this by reading
value_to_type, not in a production workflow.Validation on Python 3.12.13:
test_json_type_hintsfail before the fix (assert 5 == 5.5) and pass after it.tests/test_converter.pyandtests/test_common.py: 49 tests pass.AI disclosure: I used Claude Code to find this bug and write the fix and the tests. I reviewed the change and ran the tests locally.
🤖 Generated with Claude Code