Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: load only if there's a loader #21

Merged
merged 2 commits into from
Sep 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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