Replies: 2 comments
-
While not an answer, I have found a workaround for now. It is really inefficient because I need to go through an extra-step of JSON encoding/decoding, but it helps me to move forward with my work. The key issue I have is that the object that contain the "infinity" values are nested inside a list of "items" which is part of a list-object wrapper returned by the API. The details are irrelevant and I'll simplify the example here, but the core issue remains that a nested list contains objects with infinity values like this: {"items": [{"myvalue": "Infinity"}]} The workaround looks like this (based on the code above): from json import loads
from pydantic import TypeAdapter
# ...
@app.get("/nested-list")
def nested_list():
"""
...
"""
data = NestedList(
values=[
InfTest(value=float("inf")),
InfTest(value=float("-inf")),
InfTest(value=float("nan")),
]
)
# Use a type-adapter to encode the list of objects manually.
# This will replace the `inf` values with their string-representations. We can then
# put that back into the "nested list" which will get rid of the crash, at the cost of
# performance due to the extra json "de-/encode" step.
adapter = TypeAdapter(list[InfTest])
new_values_json = adapter.dump_json(data.values)
new_values = loads(new_values_json)
new_data = data.model_copy(update={"values": new_values})
return new_data |
Beta Was this translation helpful? Give feedback.
-
You need a custom JSON encoder that can handle infinity and NaN values according to your Pydantic model's configuration.
|
Beta Was this translation helpful? Give feedback.
-
First Check
Commit to Help
Example Code
Description
JSON does not have native support for "infinity" values. Pydantic provides a simple solution to this by setting
ser_json_inf_nan
tostrings
. Manually runningmy_object.model_dump_json()
on such an instance works as expected.However, when running it through FastAPI the application crashes with the attached traceback:
traceback.txt
The code was executed in a virtual environment with the packages listed in requirements.txt
The demo-application provides several endpoints, each demonstrating the same error from different perspecives. It also demonstates a "workaround". That workaround is limited and cannot be applied in our internal application where we noticed this issue.
Operating System
Linux
Operating System Details
No response
FastAPI Version
0.111.0
Pydantic Version
2.8.2
Python Version
3.12.0
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions