Skip to content

Commit

Permalink
Add save/load_attribute helper
Browse files Browse the repository at this point in the history
  • Loading branch information
frthjf committed May 24, 2024
1 parent 6370d2b commit 26939cb
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

# Unreleased

- Adds save/load_attribute helper
- Adds `@cachable` decorator utility

# v4.10.2
Expand Down
18 changes: 18 additions & 0 deletions src/machinable/element.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from machinable.utils import (
Jsonable,
id_from_uuid,
joinpath,
norm_version_call,
sentinel,
serialize,
Expand Down Expand Up @@ -292,6 +293,7 @@ def __init__(self, version: VersionType = None):
self._config: Optional[DictConfig] = None
self._predicate: Optional[DictConfig] = None
self._context: Optional[DictConfig] = None
self._attributes = {}
self._cache = {}
self._kwargs = {}

Expand Down Expand Up @@ -654,6 +656,22 @@ def serialize(self) -> Dict:
self.__model__.predicate = self.compute_predicate()
return self.__model__.model_dump()

def save_attribute(self, name: Union[str, List[str]], data: Any) -> str:
name = joinpath(name)

self._attributes[name] = data

return name

def load_attribute(
self, name: Union[str, List[str]], default=None
) -> Optional[Any]:
name = joinpath(name)

data = self._attributes.get(name, None)

return data if data is not None else default

@classmethod
def unserialize(cls, serialized):
return cls.from_model(cls.model()(**serialized))
Expand Down
15 changes: 15 additions & 0 deletions tests/test_element.py
Original file line number Diff line number Diff line change
Expand Up @@ -482,3 +482,18 @@ class T(Connectable):
assert Dummy.get() is dummy_1
assert Dummy.get() is not dummy_1
assert not Dummy.is_connected()


def test_element_attributes():
t = Element()

assert t.load_attribute("test") is None
assert t.save_attribute("test", None) == "test"
assert t.load_attribute("test") is None
t.save_attribute("test", "hello")
assert t.load_attribute("test") == "hello"
assert t.save_attribute(["test", "me"], True) == "test/me"
assert t.load_attribute("test/me")

t = Element()
assert t.load_attribute("test") is None

0 comments on commit 26939cb

Please sign in to comment.