Skip to content

Commit b7de96f

Browse files
committed
perf: Use maps to make JSON encoder faster
1 parent a29e028 commit b7de96f

1 file changed

Lines changed: 16 additions & 10 deletions

File tree

‎packages/griffelib/src/griffe/_internal/encoders.py‎

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121

2222
import json
2323
from pathlib import Path, PosixPath, WindowsPath
24-
from typing import TYPE_CHECKING, Any
24+
from typing import TYPE_CHECKING, Any, cast
2525

2626
from griffe._internal import expressions
2727
from griffe._internal.enumerations import Kind, ParameterKind, TypeParameterKind
@@ -45,6 +45,14 @@
4545
if TYPE_CHECKING:
4646
from collections.abc import Callable
4747

48+
_expression_class_map: dict[str, type[expressions.Expr]] = {
49+
name: value
50+
for name, value in vars(expressions).items()
51+
if isinstance(value, type) and issubclass(value, expressions.Expr)
52+
}
53+
_parameter_kinds = frozenset(ParameterKind.__members__.values())
54+
_type_parameter_kinds = frozenset(TypeParameterKind.__members__.values())
55+
4856
_json_encoder_map: dict[type, Callable[[Any], Any]] = {
4957
Path: str,
5058
PosixPath: str,
@@ -117,7 +125,7 @@ def _load_decorators(obj_dict: dict) -> list[Decorator]:
117125

118126
def _load_expression(expression: dict) -> expressions.Expr:
119127
# The expression class name is stored in the `cls` key-value.
120-
cls = getattr(expressions, expression.pop("cls"))
128+
cls = _expression_class_map[expression.pop("cls")]
121129
expr = cls(**expression)
122130

123131
# For attributes, we need to re-attach names (`values`) together,
@@ -127,9 +135,9 @@ def _load_expression(expression: dict) -> expressions.Expr:
127135
# as `(a or b)` is not a name and wouldn't allow to resolve `c`.
128136
if cls is expressions.ExprAttribute:
129137
previous = None
130-
for value in expr.values:
138+
for value in cast("expressions.ExprAttribute", expr).values:
131139
if previous is not None:
132-
value.parent = previous
140+
cast("expressions.ExprName", value).parent = previous
133141
if isinstance(value, expressions.ExprName):
134142
previous = value
135143
return expr
@@ -377,13 +385,11 @@ def json_decoder(
377385
# Load objects and parameters.
378386
if "kind" in obj_dict:
379387
kind = obj_dict["kind"]
380-
if kind in _loader_map:
381-
return _loader_map[kind](obj_dict)
382-
# YORE: EOL 3.11: Replace `.__members__.values()` with `` within line.
383-
if kind in ParameterKind.__members__.values():
388+
if loader := _loader_map.get(kind):
389+
return loader(obj_dict)
390+
if kind in _parameter_kinds:
384391
return _load_parameter(obj_dict)
385-
# YORE: EOL 3.11: Replace `.__members__.values()` with `` within line.
386-
if kind in TypeParameterKind.__members__.values():
392+
if kind in _type_parameter_kinds:
387393
return _load_type_parameter(obj_dict)
388394

389395
# Return dict as is.

0 commit comments

Comments
 (0)