diff --git a/bob/io/base/__init__.py b/bob/io/base/__init__.py index ba3ccf535cfd42785c75a47e8b1c8e51de553a3b..d84289b2a75e4f931e5d45ace768a23299d83605 100644 --- a/bob/io/base/__init__.py +++ b/bob/io/base/__init__.py @@ -39,6 +39,9 @@ class HDF5File(HDF5File_C): """ return self.has_key(x) + def __iter__(self): + return iter(self.keys()) + def _is_string(s): """Returns ``True`` if the given object is a string diff --git a/bob/io/base/test_hdf5.py b/bob/io/base/test_hdf5.py index 0c12f2b7407be074af4df9efaaf1bfa325fce235..fcc5811ce60903393cfc6a8695e6ebc682e8db88 100644 --- a/bob/io/base/test_hdf5.py +++ b/bob/io/base/test_hdf5.py @@ -480,6 +480,7 @@ def test_copy_constructor(): assert "/Test/Data" in shallow assert hdf5.filename == shallow.filename assert hdf5.keys() == shallow.keys() + assert [key for key in hdf5] == shallow.keys() assert hdf5.cwd == shallow.cwd assert not deep.has_group("/Test") diff --git a/doc/guide.rst b/doc/guide.rst index 0554cd4c7233c7f9f3fa7830e7d35f6d3e5920e5..7ecdd8c09f1fd12511505506baf8e1a4a6eb3558 100644 --- a/doc/guide.rst +++ b/doc/guide.rst @@ -257,6 +257,27 @@ the variable `my_array` as an arrayset using :py:meth:`bob.io.base.HDF5File.read`. In this case, each position readout would return a 1D uint8 array instead of a 2D array. + +Pythonic operations on HDF5 files +--------------------------------- + +You can use some Pythonic opertations on :py:class:`bob.io.base.HDF5File`. +You can iterate over :py:class:`bob.io.base.HDF5File` objects to get an +iterable of keys instead of calling +:py:meth:`bob.io.base.HDF5File.keys`. You can also use the ``in`` keyword +instead of calling :py:meth:`bob.io.base.HDF5File.has_key`. For example: + +.. doctest:: + + >>> keys = f.keys() # Get a list of keys + >>> keys == [key for key in f] # instead you can also iterate over keys + True + >>> f.has_key('arrayset') + True + >>> 'arrayset' in f # you can use the `in` operator instead of `has_key` + True + + Array interfaces ----------------