Skip to content

BUG: close hdf store on any error #28429

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

Closed
Closed
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -727,6 +727,7 @@ I/O
- Bug in :meth:`DataFrame.to_clipboard` which did not work reliably in ipython (:issue:`22707`)
- Bug in :func:`read_json` where default encoding was not set to ``utf-8`` (:issue:`29565`)
- Bug in :class:`PythonParser` where str and bytes were being mixed when dealing with the decimal field (:issue:`29650`)
- :meth:`read_hdf` now closes the store on any error thrown (:issue:`28430`)
-

Plotting
Expand Down
15 changes: 6 additions & 9 deletions pandas/io/pytables.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,15 +426,12 @@ def read_hdf(
chunksize=chunksize,
auto_close=auto_close,
)
except (ValueError, TypeError, KeyError):
if not isinstance(path_or_buf, HDFStore):
# if there is an error, close the store if we opened it.
try:
store.close()
except AttributeError:
pass

raise
finally:
# if there is an error, close the store if we opened it.
try:
store.close()
except AttributeError:
pass


def _is_metadata_of(group: "Node", parent_group: "Node") -> bool:
Expand Down
19 changes: 19 additions & 0 deletions pandas/tests/io/pytables/test_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,25 @@ def check_default_mode():
check("w")
check_default_mode()

def test_store_closed_on_error(self, mocker):
"""check hdf store is closed whichever error occurs"""
mocker.patch("pandas.io.pytables.HDFStore.select").side_effect = AssertionError(
"Gaps in blk ref_locs"
)
df = tm.makeDataFrame()
with ensure_clean_path(self.path) as path:
df.to_hdf(path, "df")
try:
pd.read_hdf(path, "df")
except AssertionError: # this is expected, because of our mock
pass
try:
HDFStore(path, mode="w")
except ValueError as exc:
pytest.fail(
"store not closed properly, got error {exc}".format(exc=exc)
)

def test_reopen_handle(self, setup_path):

with ensure_clean_path(setup_path) as path:
Expand Down