Skip to content

Commit

Permalink
perf: load only if there's a loader (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
rilshok committed Sep 4, 2024
2 parents 1a6a8be + 9020876 commit 73c9115
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
2 changes: 1 addition & 1 deletion src/iokit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"save_file",
"save_temp",
]
__version__ = "0.1.5"
__version__ = "0.1.6"

from .extensions import Dat, Env, Gzip, Json, Jsonl, Tar, Txt, Yaml
from .state import State, filter_states, find_state
Expand Down
22 changes: 14 additions & 8 deletions src/iokit/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,20 +134,26 @@ def _by_suffix(cls, suffix: str) -> Type[Self]:
for kls in cls.__subclasses__():
with suppress(ValueError):
return kls._by_suffix(suffix)
return cls
raise ValueError(f"Unknown state suffix '{suffix}'")

def cast(self) -> "State":
klass = self._by_suffix(self.name.suffix)
state = klass.__new__(klass)
setattr(state, "_data", self.data)
setattr(state, "_name", self.name)
setattr(state, "_time", self.time)
return state
with suppress(ValueError):
klass = self._by_suffix(self.name.suffix)
state = klass.__new__(klass)
setattr(state, "_data", self.data)
setattr(state, "_name", self.name)
setattr(state, "_time", self.time)
return state
return self

def load(self) -> Any:
if not self.name.suffix:
return self.data.getvalue()
return self.cast().load()
state = self.cast()
if type(state) is State: # pylint: disable=unidiomatic-typecheck
msg = f"Cannot load state with suffix '{self.name.suffix}'"
raise NotImplementedError(msg)
return state.load()


def filter_states(states: Iterable[State], pattern: str) -> Generator[State, None, None]:
Expand Down

0 comments on commit 73c9115

Please sign in to comment.