Skip to content

Commit 8a78903

Browse files
committed
Implement basic caching for ModResourceLoader._load_path
1 parent 869074b commit 8a78903

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

src/hexdoc/core/loader.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from textwrap import dedent
1111
from typing import Any, Callable, Literal, Self, Sequence, TypeVar, overload
1212

13-
from pydantic import SkipValidation
13+
from pydantic import Field, SkipValidation
1414
from pydantic.dataclasses import dataclass
1515

1616
from hexdoc.model import DEFAULT_CONFIG, HexdocModel
@@ -50,6 +50,7 @@ class ModResourceLoader(ValidationContext):
5050
export_dir: Path | None
5151
resource_dirs: Sequence[PathResourceDir]
5252
_stack: SkipValidation[ExitStack]
53+
_cache: dict[Path, str] = Field(default_factory=dict)
5354

5455
@classmethod
5556
def clean_and_load_all(
@@ -447,12 +448,17 @@ def _load_path(
447448
decode: Callable[[str], _T] = decode_json_dict,
448449
export: ExportFn[_T] | Literal[False] | None = None,
449450
) -> _T:
450-
if not path.is_file():
451-
raise FileNotFoundError(path)
451+
if path in self._cache:
452+
data = self._cache[path]
453+
logger.debug(f"Fetching {path} from cache")
454+
else:
455+
if not path.is_file():
456+
raise FileNotFoundError(path)
452457

453-
logger.debug(f"Loading {path}")
458+
logger.debug(f"Loading {path}")
454459

455-
data = path.read_text("utf-8")
460+
data = path.read_text("utf-8")
461+
self._cache[path] = data
456462
value = decode(data)
457463

458464
if resource_dir.reexport and export is not False:

0 commit comments

Comments
 (0)