From b3df0e690ee06e1b3f2405b3bd93206c87da79ec Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Mon, 1 Jun 2026 01:24:36 +0000 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=20Bolt:=20Optimize=20JSON=20parsing?= =?UTF-8?q?=20in=20Pydantic=20validators?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Optimized the parsing of JSON string types in Pydantic validators by adding a `functools.lru_cache` to a private helper that returns an immutable tuple, returning a list copy in the public validator to prevent cache pollution. --- src/app/schemas/pokemon.py | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/src/app/schemas/pokemon.py b/src/app/schemas/pokemon.py index 7111dad..b31197c 100644 --- a/src/app/schemas/pokemon.py +++ b/src/app/schemas/pokemon.py @@ -1,10 +1,36 @@ """Pokemon module.""" +import functools import json +import logging from typing import Any from pydantic import BaseModel, ConfigDict, field_validator +logger = logging.getLogger(__name__) + + +@functools.lru_cache +def _parse_types_json(value: str) -> tuple[str, ...]: + """Private helper to parse and cache JSON types string into an immutable tuple. + + Args: + value: The JSON string to parse. + + Returns: + A tuple of parsed types. + + Raises: + ValueError: If the string is not valid JSON or not a list. + """ + try: + parsed = json.loads(value) + if not isinstance(parsed, list): + raise ValueError("invalid types format") + return tuple(parsed) + except json.JSONDecodeError as e: + raise ValueError("malformed types JSON") from e + def parse_pokemon_types(value: Any) -> Any: """Helper function to parse the types JSON string. @@ -19,13 +45,7 @@ def parse_pokemon_types(value: Any) -> Any: ValueError: If the string is not valid JSON or not a list. """ if isinstance(value, str): - try: - parsed = json.loads(value) - if not isinstance(parsed, list): - raise ValueError("invalid types format") - return parsed - except json.JSONDecodeError as e: - raise ValueError("malformed types JSON") from e + return list(_parse_types_json(value)) return value