Local storage helpers.

class LocalStorage

Local storage object.

Example:

1 from pathlib import Path
2
3 class User(LocalStorage):
4 '''User account object'''
5
6 name: str
7
8 user = User(name="John", path=Path("user.json"))
9 print (user.name)
10 user.store()
11
12 user = User.load(Path("user.json"))
13 print (user.name)

Note: When deriving from the LocalStorage class, path needs to be defined as a class variable.

Properties

path
t.Optional[Path]

Class property

Methods

def to_json

Convert object to JSON dictionary.

Returns

returns
t.Dict

No description provided

1def to_json(self) -> t.Dict:
2 """Convert object to JSON dictionary."""
3 return self.model_dump()

def from_json

Load from json object.

Parameters

obj
t.DictRequired

No description provided

path
t.Optional[Path]

No description provided

Returns

returns
tx.Self

No description provided

1@classmethod
2def from_json(cls, obj: t.Dict, path: t.Optional[Path]=None) -> tx.Self:
3 """Load from json object."""
4 return cls(**obj, path=path)

def store

Store object as a JSON file.

1def store(self) -> None:
2 """Store object as a JSON file."""
3 if self.path is None:
4 raise ValueError(f'Value of `path` is not set for `{self.__class__.__name__}`')
5 self.path.parent.mkdir(parents=True, exist_ok=True)
6 data = self.to_json()
7 if 'path' in data:
8 del data['path']
9 logger.debug('Storing %s to %s', self.__class__.__name__, self.path)
10 self.path.write_text(json.dumps(data, indent=2), encoding='utf-8')

def load

Load user account from cache.

Parameters

path
PathRequired

No description provided

Returns

returns
tx.Self

No description provided

1@classmethod
2def load(cls, path: Path) -> tx.Self:
3 """Load user account from cache."""
4 return cls.from_json(obj=json.loads(path.read_text(encoding='utf-8')), path=path)