Skip to content

Represent serialized floats to approximately python float precision #318

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

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
7 changes: 5 additions & 2 deletions gql/dsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,10 +106,13 @@ def ast_from_serialized_value_untyped(serialized: Any) -> Optional[ValueNode]:
return BooleanValueNode(value=serialized)

if isinstance(serialized, int):
return IntValueNode(value=f"{serialized:d}")
return IntValueNode(value=str(serialized))

if isinstance(serialized, float) and isfinite(serialized):
return FloatValueNode(value=f"{serialized:g}")
value = str(serialized)
if value.endswith(".0"):
value = value[:-2]
return FloatValueNode(value=value)

if isinstance(serialized, str):
return StringValueNode(value=serialized)
Expand Down
16 changes: 16 additions & 0 deletions tests/starwars/test_dsl.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import pytest
from graphql import (
FloatValueNode,
GraphQLError,
GraphQLFloat,
GraphQLID,
GraphQLInt,
GraphQLList,
Expand Down Expand Up @@ -87,6 +89,20 @@ def test_ast_from_value_with_non_null_type_and_none():
assert "Received Null value for a Non-Null type Int." in str(exc_info.value)


def test_ast_from_value_float_precision():

# Checking precision of float serialization
# See https://github.com/graphql-python/graphql-core/pull/164

assert ast_from_value(123456789.01234567, GraphQLFloat) == FloatValueNode(
value="123456789.01234567"
)

assert ast_from_value(1.1, GraphQLFloat) == FloatValueNode(value="1.1")

assert ast_from_value(123.0, GraphQLFloat) == FloatValueNode(value="123")


def test_ast_from_serialized_value_untyped_typeerror():
with pytest.raises(TypeError) as exc_info:
ast_from_serialized_value_untyped(GraphQLInt)
Expand Down