use load_or_create more functionally

This commit is contained in:
JJJHolscher 2024-11-14 11:50:48 +01:00
parent 90146757f1
commit 0ced06bfc4
2 changed files with 32 additions and 28 deletions

View File

@ -1,7 +1,7 @@
[project]
name = "jo3util"
version = "0.0.18"
version = "0.0.19"
description = ""
dependencies = []
dynamic = ["readme"]

View File

@ -69,37 +69,16 @@ class load_or_create:
self.save_args=save_args
self.save_json=save_json
self.plain_text=plain_text
self.obj_to_args = {}
# To be initialied by Loc.
self.fn = lambda x: x
self.arg_names = []
def __call__(self, fn):
return inner(self, fn)
return Loc(self, fn)
class inner(load_or_create):
def __init__(self, parent, fn):
self.__dict__.update(parent.__dict__)
self.fn = fn
self.arg_names = [p.name for p in inspect.signature(fn).parameters.values()]
self.obj_to_args = dict()
def __call__(self, *args, **kwargs):
# Store the keyword arguments into json and hash it to get the storage path.
path = self.path(*args, **kwargs)
merged_args = self.args_to_kwargs(args, kwargs, path=path)
obj = self.load_wrapper(**merged_args)
if obj is not None:
if "file" in self.save_arg_names: self.hash_obj({"path": path} | kwargs)
return obj
obj = self.fn(*args, **kwargs)
if obj is None: return obj
self.save_wrapper(obj, *args, **{"path": path} | kwargs)
if "file" in self.save_arg_names: self.hash_obj({"path": path} | kwargs)
if self.save_json: path.with_suffix(".kwargs.json").write_bytes(self.to_json(**kwargs))
return obj
def args_to_kwargs(self, args, kwargs, **extra):
return extra | kwargs | {self.arg_names[i]: a for i, a in enumerate(args)}
@ -243,3 +222,28 @@ class inner(load_or_create):
return LoadOrCreateCFG(*args, **kwargs)
class Loc(load_or_create):
def __init__(self, parent, fn):
self.__dict__.update(parent.__dict__)
self.fn = fn
self.arg_names = [p.name for p in inspect.signature(fn).parameters.values()]
def __call__(self, *args, **kwargs):
# Store the keyword arguments into json and hash it to get the storage path.
path = self.path(*args, **kwargs)
merged_args = self.args_to_kwargs(args, kwargs, path=path)
obj = self.load_wrapper(**merged_args)
if obj is not None:
if "file" in self.save_arg_names: self.hash_obj({"path": path} | kwargs)
return obj
obj = self.fn(*args, **kwargs)
if obj is None: return obj
self.save_wrapper(obj, *args, **{"path": path} | kwargs)
if "file" in self.save_arg_names: self.hash_obj({"path": path} | kwargs)
if self.save_json: path.with_suffix(".kwargs.json").write_bytes(self.to_json(**kwargs))
return obj