Skip to content

Commit 1a90c7e

Browse files
committed
Snaps: _len is a cached property
1 parent b32094b commit 1a90c7e

File tree

1 file changed

+21
-20
lines changed

1 file changed

+21
-20
lines changed

src/stagpy/stagyydata.py

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,6 @@ def __init__(self, sdat: StagyyData):
388388
self.sdat = sdat
389389
self._isteps: dict[int, int | None] = {}
390390
self._all_isteps_known = False
391-
self._len: int | None = None
392391

393392
def __repr__(self) -> str:
394393
return f"{self.sdat!r}.snaps"
@@ -429,26 +428,28 @@ def __delitem__(self, isnap: int | None) -> None:
429428
istep = self._isteps.get(isnap)
430429
del self.sdat.steps[istep]
431430

431+
@cached_property
432+
def _len(self) -> int:
433+
length = -1
434+
if self.sdat.hdf5:
435+
isnap = -1
436+
for isnap, istep in stagyyparsers.read_time_h5(self.sdat.hdf5):
437+
self._bind(isnap, istep)
438+
length = isnap
439+
self._all_isteps_known = True
440+
if length < 0:
441+
out_stem = re.escape(self.sdat.par.legacy_output("_").name[:-1])
442+
rgx = re.compile(f"^{out_stem}_([a-zA-Z]+)([0-9]{{5}})$")
443+
fstems = set(fstem for fstem in phyvars.FIELD_FILES)
444+
for fname in self.sdat._files:
445+
match = rgx.match(fname.name)
446+
if match is not None and match.group(1) in fstems:
447+
length = max(int(match.group(2)), length)
448+
if length < 0:
449+
raise error.NoSnapshotError(self.sdat)
450+
return length + 1
451+
432452
def __len__(self) -> int:
433-
if self._len is None:
434-
length = -1
435-
if self.sdat.hdf5:
436-
isnap = -1
437-
for isnap, istep in stagyyparsers.read_time_h5(self.sdat.hdf5):
438-
self._bind(isnap, istep)
439-
length = isnap
440-
self._all_isteps_known = True
441-
if length < 0:
442-
out_stem = re.escape(self.sdat.par.legacy_output("_").name[:-1])
443-
rgx = re.compile(f"^{out_stem}_([a-zA-Z]+)([0-9]{{5}})$")
444-
fstems = set(fstem for fstem in phyvars.FIELD_FILES)
445-
for fname in self.sdat._files:
446-
match = rgx.match(fname.name)
447-
if match is not None and match.group(1) in fstems:
448-
length = max(int(match.group(2)), length)
449-
if length < 0:
450-
raise error.NoSnapshotError(self.sdat)
451-
self._len = length + 1
452453
return self._len
453454

454455
def __iter__(self) -> Iterator[Step]:

0 commit comments

Comments
 (0)