Group Objects

Creating and using groups

Groups are the container mechanism by which HDF5 files are organized. From a Python perspective, they operate somewhat like dictionaries. In this case the “keys” are the names of group members, and the “values” are the members themselves (Group and Dataset) objects.

Group objects also contain most of the machinery which makes HDF5 useful. The File object does double duty as the HDF5 root group, and serves as your entry point into the file:

>>> f = h5py.File('foo.hdf5','w')
>>> f.name
'/'
>>> f.keys()
[]

New groups are easy to create:

>>> grp = f.create_group("bar")
>>> grp.name
'/bar'
>>> subgrp = grp.create_group("baz")
>>> subgrp.name
'/bar/baz'

Datasets are also created by a Group method:

>>> dset = subgrp.create_dataset("MyDS", (100,100), dtype='i')
>>> dset.name
'/bar/baz/MyDS'

Accessing objects

Groups implement a subset of the Python dictionary convention. They have methods like keys(), values() and support iteration. Most importantly, they support the indexing syntax, and standard exceptions:

>>> myds = subgrp["MyDS"]
>>> missing = subgrp["missing"]
KeyError: "Name doesn't exist (Symbol table: Object not found)"

Objects can be deleted from the file using the standard syntax:

>>> del subgroup["MyDataset"]

Group objects implement the following subset of the Python “mapping” interface:

  • Container syntax: if name in group
  • Iteration; yields member names: for name in group
  • Length: len(group)
  • keys()
  • values()
  • items()
  • iterkeys()
  • itervalues()
  • iteritems()
  • __setitem__()
  • __getitem__()
  • __delitem__()
  • get()

Python 3 dict interface

When using h5py from Python 3, the keys(), values() and items() methods will return view-like objects instead of lists. These objects support containership testing and iteration, but can’t be sliced like lists.

The iterkeys(), itervalues(), and iteritems() methods are likewise not available in Python 3. You may wish to use the standard conversion script 2to3 which ships with Python to accomodate these changes.

Reference

class h5py.Group(bind)

Represents an HDF5 group.

``Group`` methods

__setitem__(name, obj)

Add an object to the group. The name must not already be in use.

The action taken depends on the type of object assigned:

Named HDF5 object (Dataset, Group, Datatype)
A hard link is created at “name” which points to the given object.
SoftLink or ExternalLink
Create the corresponding link.
Numpy ndarray
The array is converted to a dataset object, with default settings (contiguous storage, etc.).
Numpy dtype
Commit a copy of the datatype as a named datatype in the file.
Anything else
Attempt to convert it to an ndarray and store it. Scalar values are stored as scalar datasets. Raise ValueError if we can’t understand the resulting array dtype.
__getitem__(name)

Open an object in the file

create_group(name)

Create and return a new subgroup.

Name may be absolute or relative. Fails if the target name already exists.

create_dataset(name, shape=None, dtype=None, data=None, **kwds)

Create a new HDF5 dataset

name
Name of the dataset (absolute or relative). Provide None to make an anonymous dataset.
shape
Dataset shape. Use “()” for scalar datasets. Required if “data” isn’t provided.
dtype
Numpy dtype or string. If omitted, dtype(‘f’) will be used. Required if “data” isn’t provided; otherwise, overrides data array’s dtype.
data
Provide data to initialize the dataset. If used, you can omit shape and dtype arguments.

Keyword-only arguments:

chunks
(Tuple) Chunk shape, or True to enable auto-chunking.
maxshape
(Tuple) Make the dataset resizable up to this shape. Use None for axes you want to be unlimited.
compression
(String) Compression strategy. Legal values are ‘gzip’, ‘szip’, ‘lzf’. Can also use an integer in range(10) indicating gzip.
compression_opts
Compression settings. This is an integer for gzip, 2-tuple for szip, etc.
shuffle
(T/F) Enable shuffle filter.
fletcher32
(T/F) Enable fletcher32 error detection.
fillvalue
(Scalar) Use this value for uninitialized parts of the dataset.
require_group(name)

Return a group, creating it if it doesn’t exist.

TypeError is raised if something with that name already exists that isn’t a group.

require_dataset(name, shape, dtype, exact=False, **kwds)

Open a dataset, creating it if it doesn’t exist.

If keyword “exact” is False (default), an existing dataset must have the same shape and a conversion-compatible dtype to be returned. If True, the shape and dtype must match exactly.

Other dataset keywords (see create_dataset) may be provided, but are only used if a new dataset is to be created.

Raises TypeError if an incompatible object already exists, or if the shape or dtype don’t match according to the above rules.

copy(source, dest, name=None)

Copy an object or group.

The source can be a path, Group, Dataset, or Datatype object. The destination can be either a path or a Group object. The source and destinations need not be in the same file.

If the source is a Group object, all objects contained in that group will be copied recursively.

When the destination is a Group object, by default the target will be created in that group with its current name (basename of obj.name). You can override that by setting “name” to a string.

Example:

>>> f = File('myfile.hdf5')
>>> f.listnames()
['MyGroup']
>>> f.copy('MyGroup', 'MyCopy')
>>> f.listnames()
['MyGroup', 'MyCopy']
visit(func)

Recursively visit all names in this group and subgroups (HDF5 1.8).

You supply a callable (function, method or callable object); it will be called exactly once for each link in this group and every group below it. Your callable must conform to the signature:

func(<member name>) => <None or return value>

Returning None continues iteration, returning anything else stops and immediately returns that value from the visit method. No particular order of iteration within groups is guranteed.

Example:

>>> # List the entire contents of the file
>>> f = File("foo.hdf5")
>>> list_of_names = []
>>> f.visit(list_of_names.append)
visititems(func)

Recursively visit names and objects in this group (HDF5 1.8).

You supply a callable (function, method or callable object); it will be called exactly once for each link in this group and every group below it. Your callable must conform to the signature:

func(<member name>, <object>) => <None or return value>

Returning None continues iteration, returning anything else stops and immediately returns that value from the visit method. No particular order of iteration within groups is guranteed.

Example:

# Get a list of all datasets in the file >>> mylist = [] >>> def func(name, obj): ... if isinstance(obj, Dataset): ... mylist.append(name) ... >>> f = File(‘foo.hdf5’) >>> f.visititems(func)

Dictionary-like methods

keys()

Get a list containing member names

values()

Get a list containing member objects

items()

Get a list of tuples containing (name, object) pairs

iterkeys()

Get an iterator over member names

itervalues()

Get an iterator over member objects

iteritems()

Get an iterator over (name, object) pairs

get(name, default=None, getclass=False, getlink=False)

Retrieve an item or other information.

“name” given only:
Return the item, or “default” if it doesn’t exist
“getclass” is True:
Return the class of object (Group, Dataset, etc.), or “default” if nothing with that name exists
“getlink” is True:
Return HardLink, SoftLink or ExternalLink instances. Return “default” if nothing with that name exists.
“getlink” and “getclass” are True:
Return HardLink, SoftLink and ExternalLink classes. Return “default” if nothing with that name exists.

Example:

>>> cls = group.get('foo', getclass=True)
>>> if cls == SoftLink:
...     print '"foo" is a soft link!'

Properties common to all HDF5 objects:

file

Return a File instance associated with this object

parent

Return the parent group of this object.

This is always equivalent to obj.file[posixpath.dirname(obj.name)]. ValueError if this object is anonymous.

name

Return the full name of this object. None if anonymous.

id

Low-level identifier appropriate for this object

ref

An (opaque) HDF5 reference to this object

attrs

Attributes attached to this object

Table Of Contents

Previous topic

File Objects

Next topic

Datasets

This Page