Skip to content

ENH: add contextmanager to HDFStore (#8791) #8958

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

Merged
merged 1 commit into from
Dec 4, 2014
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 doc/source/io.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2348,7 +2348,7 @@ Closing a Store, Context Manager

# Working with, and automatically closing the store with the context
# manager
with get_store('store.h5') as store:
with HDFStore('store.h5') as store:
store.keys()

.. ipython:: python
Expand Down
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.15.2.txt
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ Enhancements
- Added ``Timedelta.to_timedelta64`` method to the public API (:issue:`8884`).
- Added ``gbq.generate_bq_schema`` function to the gbq module (:issue:`8325`).
- ``Series`` now works with map objects the same way as generators (:issue:`8909`).
- Added context manager to ``HDFStore`` (:issue:`8791`). Now with HDFStore('path') as store: should also close to store. get_store will be deprecated in the future.

.. _whatsnew_0152.performance:

Expand Down
41 changes: 13 additions & 28 deletions pandas/io/pytables.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,33 +251,6 @@ def _tables():

return _table_mod

@contextmanager
def get_store(path, **kwargs):
"""
Creates an HDFStore instance. This function can be used in a with statement

Parameters
----------
same as HDFStore

Examples
--------
>>> from pandas import DataFrame
>>> from numpy.random import randn
>>> bar = DataFrame(randn(10, 4))
>>> with get_store('test.h5') as store:
... store['foo'] = bar # write to HDF5
... bar = store['foo'] # retrieve
"""
store = None
try:
store = HDFStore(path, **kwargs)
yield store
finally:
if store is not None:
store.close()


# interface to/from ###
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn'tactually mean to deprecate this. I said we should think about it. Pls revert this section.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But if we deprecate it or not, get_store can just be the same as HDFStore ? (get_store = HDFStore)


def to_hdf(path_or_buf, key, value, mode=None, complevel=None, complib=None,
Expand All @@ -289,7 +262,7 @@ def to_hdf(path_or_buf, key, value, mode=None, complevel=None, complib=None,
f = lambda store: store.put(key, value, **kwargs)

if isinstance(path_or_buf, string_types):
with get_store(path_or_buf, mode=mode, complevel=complevel,
with HDFStore(path_or_buf, mode=mode, complevel=complevel,
complib=complib) as store:
f(store)
else:
Expand Down Expand Up @@ -493,6 +466,12 @@ def __unicode__(self):

return output

def __enter__(self):
return self

def __exit__(self, exc_type, exc_value, traceback):
self.close()

def keys(self):
"""
Return a (potentially unordered) list of the keys corresponding to the
Expand Down Expand Up @@ -1288,6 +1267,12 @@ def _read_group(self, group, **kwargs):
return s.read(**kwargs)


def get_store(path, **kwargs):
""" Backwards compatible alias for ``HDFStore``
"""
return HDFStore(path, **kwargs)


class TableIterator(object):

""" define the iteration interface on a table
Expand Down
27 changes: 23 additions & 4 deletions pandas/io/tests/test_pytables.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,25 @@ def test_factory_fun(self):
finally:
safe_remove(self.path)

def test_context(self):
try:
with HDFStore(self.path) as tbl:
raise ValueError('blah')
except ValueError:
pass
finally:
safe_remove(self.path)

try:
with HDFStore(self.path) as tbl:
tbl['a'] = tm.makeDataFrame()

with HDFStore(self.path) as tbl:
self.assertEqual(len(tbl), 1)
self.assertEqual(type(tbl['a']), DataFrame)
finally:
safe_remove(self.path)

def test_conv_read_write(self):

try:
Expand Down Expand Up @@ -334,10 +353,10 @@ def test_api_default_format(self):

pandas.set_option('io.hdf.default_format','table')
df.to_hdf(path,'df3')
with get_store(path) as store:
with HDFStore(path) as store:
self.assertTrue(store.get_storer('df3').is_table)
df.to_hdf(path,'df4',append=True)
with get_store(path) as store:
with HDFStore(path) as store:
self.assertTrue(store.get_storer('df4').is_table)

pandas.set_option('io.hdf.default_format',None)
Expand Down Expand Up @@ -463,11 +482,11 @@ def check(mode):
# context
if mode in ['r','r+']:
def f():
with get_store(path,mode=mode) as store:
with HDFStore(path,mode=mode) as store:
pass
self.assertRaises(IOError, f)
else:
with get_store(path,mode=mode) as store:
with HDFStore(path,mode=mode) as store:
self.assertEqual(store._handle.mode, mode)

with ensure_clean_path(self.path) as path:
Expand Down