Skip to content

Commit

Permalink
[cache] Refactor to reduced signature.
Browse files Browse the repository at this point in the history
This brings more robustness to the codebase: users cannot accidentally create file name collisions in the cache dir.
  • Loading branch information
SepandKashani committed Mar 14, 2024
1 parent 0702ea9 commit fdf8856
Showing 1 changed file with 23 additions and 6 deletions.
29 changes: 23 additions & 6 deletions src/pyxu/util/cache.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,41 @@
import pyxu.info.config as config
import hashlib

import pyxu.info.config as pxcfg

__all__ = [
"cache_module",
]


def cache_module(name: str, code: str):
def cache_module(code: str) -> str:
"""
Update a specific module in the dynamic module cache.
Save `code` as an importable module in Pyxu's dynamic module cache.
The cached module is updated only if changes are detected.
Parameters
----------
name: str
Name of the module to update.
code: str
Contents of the module.
When stored in a file, `code` should be a valid Python module.
Returns
-------
module_name: str
Name of the module in :py:func:`~pyxu.info.config.cache_dir`.
Notes
-----
`module_name` is chosen automatically based on the file's contents.
"""
module_path = config.cache_dir / f"{name}.py"
# Compute a unique name
h = hashlib.blake2b(code.encode("utf-8"), digest_size=8)
module_name = "cached_" + h.hexdigest()

pxcfg.cache_dir().mkdir(parents=True, exist_ok=True)
module_path = pxcfg.cache_dir() / f"{module_name}.py"

# Do we overwrite?
write = True
if module_path.exists():
with open(module_path, mode="r") as f:
Expand All @@ -31,3 +46,5 @@ def cache_module(name: str, code: str):
if write:
with open(module_path, mode="w") as f:
f.write(code)

return module_name

0 comments on commit fdf8856

Please sign in to comment.