|
1 | 1 | import copy
|
2 | 2 | from typing import List, Optional, Iterable, Dict
|
3 |
| -from pydantic import BaseModel, field_serializer |
| 3 | +from pydantic import BaseModel |
4 | 4 |
|
5 | 5 |
|
6 | 6 | class Error(BaseModel):
|
@@ -211,13 +211,29 @@ class Logs(BaseModel):
|
211 | 211 | "List of strings printed to stderr by prints, subprocesses, etc."
|
212 | 212 |
|
213 | 213 |
|
| 214 | +def serialize_results(results: List[Result]) -> List[Dict[str, str]]: |
| 215 | + """ |
| 216 | + Serializes the results to JSON. |
| 217 | + This method is used by the Pydantic JSON encoder. |
| 218 | + """ |
| 219 | + serialized = [] |
| 220 | + for result in results: |
| 221 | + serialized_dict = {key: result[key] for key in result.formats()} |
| 222 | + serialized_dict["text"] = result.text |
| 223 | + serialized.append(serialized_dict) |
| 224 | + return serialized |
| 225 | + |
| 226 | + |
214 | 227 | class Execution(BaseModel):
|
215 | 228 | """
|
216 | 229 | Represents the result of a cell execution.
|
217 | 230 | """
|
218 | 231 |
|
219 | 232 | class Config:
|
220 | 233 | arbitrary_types_allowed = True
|
| 234 | + json_encoders = { |
| 235 | + List[Result]: serialize_results, |
| 236 | + } |
221 | 237 |
|
222 | 238 | results: List[Result] = []
|
223 | 239 | "List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots)."
|
@@ -245,19 +261,6 @@ def to_json(self) -> str:
|
245 | 261 | """
|
246 | 262 | return self.model_dump_json(exclude_none=True)
|
247 | 263 |
|
248 |
| - @field_serializer("results", when_used="json") |
249 |
| - def serialize_results(results: List[Result]) -> List[Dict[str, str]]: |
250 |
| - """ |
251 |
| - Serializes the results to JSON. |
252 |
| - This method is used by the Pydantic JSON encoder. |
253 |
| - """ |
254 |
| - serialized = [] |
255 |
| - for result in results: |
256 |
| - serialized_dict = {key: result[key] for key in result.formats()} |
257 |
| - serialized_dict["text"] = result.text |
258 |
| - serialized.append(serialized_dict) |
259 |
| - return serialized |
260 |
| - |
261 | 264 |
|
262 | 265 | class KernelException(Exception):
|
263 | 266 | """
|
|
0 commit comments