Skip to content
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

add special handling for infinity and nan #3943

Merged
merged 4 commits into from
Sep 18, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 4 additions & 0 deletions reflex/utils/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,3 +107,7 @@ class EventHandlerShadowsBuiltInStateMethod(ReflexError, NameError):

class GeneratedCodeHasNoFunctionDefs(ReflexError):
"""Raised when refactored code generated with flexgen has no functions defined."""


class PrimitiveUnserializableToJSON(ReflexError, ValueError):
"""Raised when a primitive type is unserializable to JSON. Usually with NaN and Infinity."""
19 changes: 17 additions & 2 deletions reflex/vars/number.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import dataclasses
import json
import math
import sys
from typing import (
TYPE_CHECKING,
Expand All @@ -17,7 +18,7 @@
overload,
)

from reflex.utils.exceptions import VarTypeError
from reflex.utils.exceptions import PrimitiveUnserializableToJSON, VarTypeError

from .base import (
CustomVarOperationReturn,
Expand Down Expand Up @@ -1038,7 +1039,14 @@ def json(self) -> str:

Returns:
The JSON representation of the var.

Raises:
PrimitiveUnserializableToJSON: If the var is unserializable to JSON.
"""
if math.isinf(self._var_value) or math.isnan(self._var_value):
raise PrimitiveUnserializableToJSON(
f"No valid JSON representation for {self}"
)
return json.dumps(self._var_value)

def __hash__(self) -> int:
Expand All @@ -1060,8 +1068,15 @@ def create(cls, value: float | int, _var_data: VarData | None = None):
Returns:
The number var.
"""
if math.isinf(value):
js_expr = "Infinity" if value > 0 else "-Infinity"
elif math.isnan(value):
js_expr = "NaN"
else:
js_expr = str(value)

return cls(
_js_expr=str(value),
_js_expr=js_expr,
_var_type=type(value),
_var_data=_var_data,
_var_value=value,
Expand Down
Loading