Skip to content

Commit 3ff490f

Browse files
refactor: optimize json parsing in pydantic schemas
Optimized `parse_pokemon_types` by adding a private `_parse_types_json` helper decorated with `@functools.lru_cache(maxsize=1024)`. The helper returns an immutable tuple to prevent cache pollution and the public function casts it back to a list. This significantly speeds up repeated parsing of identical JSON strings, which is common when processing lists of Pokemon.
1 parent 3d1663c commit 3ff490f

1 file changed

Lines changed: 29 additions & 7 deletions

File tree

src/app/schemas/pokemon.py

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,38 @@
11
"""Pokemon module."""
22

3+
import functools
34
import json
5+
import logging
46
from typing import Any
57

68
from pydantic import BaseModel, ConfigDict, field_validator
79

10+
logger = logging.getLogger(__name__)
11+
12+
13+
@functools.lru_cache(maxsize=1024)
14+
def _parse_types_json(value: str) -> tuple[str, ...]:
15+
"""Helper function to parse and cache the types JSON string.
16+
17+
Args:
18+
value: The value to parse, expected to be a JSON string.
19+
20+
Returns:
21+
An immutable tuple of parsed types.
22+
23+
Raises:
24+
ValueError: If the string is not valid JSON or not a list.
25+
"""
26+
try:
27+
parsed = json.loads(value)
28+
if not isinstance(parsed, list):
29+
logger.error("invalid types format: expected list")
30+
raise ValueError("invalid types format")
31+
return tuple(parsed)
32+
except json.JSONDecodeError as e:
33+
logger.error("malformed types JSON: %s", value)
34+
raise ValueError("malformed types JSON") from e
35+
836

937
def parse_pokemon_types(value: Any) -> Any:
1038
"""Helper function to parse the types JSON string.
@@ -19,13 +47,7 @@ def parse_pokemon_types(value: Any) -> Any:
1947
ValueError: If the string is not valid JSON or not a list.
2048
"""
2149
if isinstance(value, str):
22-
try:
23-
parsed = json.loads(value)
24-
if not isinstance(parsed, list):
25-
raise ValueError("invalid types format")
26-
return parsed
27-
except json.JSONDecodeError as e:
28-
raise ValueError("malformed types JSON") from e
50+
return list(_parse_types_json(value))
2951
return value
3052

3153

0 commit comments

Comments
 (0)