From cb82d05b1d7204a1bc0456284e23020a2c42dd1e Mon Sep 17 00:00:00 2001 From: "Christopher M. Pierce" Date: Tue, 30 Jun 2026 12:32:02 -0700 Subject: [PATCH 1/2] use context manager to close `h5py.File` after use --- beamphysics/particles.py | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/beamphysics/particles.py b/beamphysics/particles.py index c4899e48..1b33e4eb 100644 --- a/beamphysics/particles.py +++ b/beamphysics/particles.py @@ -4,7 +4,7 @@ from typing import Sequence, Union import numpy as np -from h5py import File +from h5py import File, Group from . import statistics from .interfaces import bmad @@ -1356,16 +1356,22 @@ def write(self, h5, name=None) -> None: """ if isinstance(h5, (str, pathlib.Path)): fname = os.path.expandvars(h5) - g = File(fname, "w") - pmd_init(g, basePath="/", particlesPath="particles") - g = g.create_group("particles") + with File(fname, "w") as f: + pmd_init(f, basePath="/", particlesPath="particles") + g = f.create_group("particles") + write_pmd_bunch(g, self, name=name) + + # Note: h5py.File is an h5py.Group so this check needs to be first elif isinstance(h5, File): pmd_init(h5, basePath="/", particlesPath="particles") g = h5.create_group("particles") - else: - g = h5 + write_pmd_bunch(g, self, name=name) - write_pmd_bunch(g, self, name=name) + elif isinstance(h5, Group): + write_pmd_bunch(h5, self, name=name) + + else: + raise ValueError(f"Expected path, h5py.File, or h5py.Group. Got {type(h5)} instead.") # Plotting # -------- From ebd931d03d5e8006f459ce199d02cd08ec3c6f7a Mon Sep 17 00:00:00 2001 From: "Christopher M. Pierce" Date: Tue, 30 Jun 2026 15:29:22 -0700 Subject: [PATCH 2/2] lint --- beamphysics/particles.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/beamphysics/particles.py b/beamphysics/particles.py index 1b33e4eb..5ca729d9 100644 --- a/beamphysics/particles.py +++ b/beamphysics/particles.py @@ -1371,7 +1371,9 @@ def write(self, h5, name=None) -> None: write_pmd_bunch(h5, self, name=name) else: - raise ValueError(f"Expected path, h5py.File, or h5py.Group. Got {type(h5)} instead.") + raise ValueError( + f"Expected path, h5py.File, or h5py.Group. Got {type(h5)} instead." + ) # Plotting # --------