PyTables User's Guide: Hierarchical datasets in Python - Release 1.3.3
Prev | Chapter 4. Library Reference | Next

# 4.4. The Group class

Instances of this class are a grouping structure containing instances of zero or more groups or leaves, together with supporting metadata.

Working with groups and leaves is similar in many ways to working with directories and files, respectively, in a Unix filesystem. As with Unix directories and files, objects in the object tree are often described by giving their full (or absolute) path names. This full path can be specified either as a string (like in `'/group1/group2'`) or as a complete object path written in natural name schema (like in `file.root.group1.group2`) as discussed in the section 1.2.

A collateral effect of the natural naming schema is that names of `Group` members must be carefully chosen to avoid colliding with existing children node names. For this reason and not to pollute the children namespace, it is explicitly forbidden to assign normal attributes to Group instances, and all existing members start with some reserved prefixes, like `_f_` (for methods) or `_v_` (for instance variables). Any attempt to set a new child node whose name starts with one of these prefixes will raise a `ValueError` exception.

Another effect of natural naming is that nodes having reserved Python names and other non-allowed Python names (like for example `$a` or `44`) can not be accessed using the `node.child` syntax. You will be forced to use `getattr(node, child)` and `delattr(node, child)` to access them.

You can also make use of the `trMap` (translation map dictionary) parameter in the `openFile` function (see section 4.1.2) in order to translate HDF5 names not suited for natural naming into more convenient ones.

## 4.4.1. Group instance variables

These instance variables are provided in addition to those in `Node` (see 4.3).

_v_nchildren

  The number of children hanging from this group.

_v_children

  Dictionary with all nodes hanging from this group.

_v_groups

  Dictionary with all groups hanging from this group.

_v_leaves

  Dictionary with all leaves hanging from this group.

_v_filters

  Default filter properties for child nodes —see 4.17.1. A shorthand for `FILTERS` attribute.

## 4.4.2. Group methods

This class defines the `__setattr__`, `__getattr__` and `__delattr__` methods, and they set, get and delete ordinary Python attributes as normally intended. In addition to that, `__getattr__` allows getting child nodes by their name for the sake of easy interaction on the command line, as long as there is no Python attribute with the same name. Groups also allow the interactive completion (when using `readline`) of the names of child nodes. For instance:

    	      nchild = group._v_nchildren  # get a Python attribute

    	      # Add a Table child called "table" under "group".
    	      h5file.createTable(group, 'table', myDescription)

    	      table = group.table          # get the table child instance
    	      group.table = 'foo'          # set a Python attribute
    	      # (PyTables warns you here about using the name of a child node.)
    	      foo = group.table            # get a Python attribute
    	      del group.table              # delete a Python attribute
    	      table = group.table          # get the table child instance again

Caveat: The following methods are documented for completeness, and they can be used without any problem. However, you should use the high-level counterpart methods in the `File` class, because these are most used in documentation and examples, and are a bit more powerful than those exposed here.

These methods are provided in addition to those in `Node` (see 4.3).

### 4.4.2.1. _f_getChild(childname)

Get the child called `childname` of this group.

If the child exists (be it visible or not), it is returned. Else, a `NoSuchNodeError` is raised.

### 4.4.2.2. _f_copy(newparent, newname, overwrite=False, recursive=False, **kwargs)

Copy this node and return the new one.

This method has the behavior described in `Node._f_copy()` (see [here]). In addition, it recognizes the following keyword arguments:

title

  The new title for the destination. If omitted or `None`, the original title is used. This only applies to the topmost node in recursive copies.

filters

  Specifying this parameter overrides the original filter properties in the source node. If specified, it must be an instance of the `Filters` class (see section 4.17.1). The default is to copy the filter properties from the source node.

copyuserattrs

  You can prevent the user attributes from being copied by setting this parameter to `False`. The default is to copy them.

stats

  This argument may be used to collect statistics on the copy process. When used, it should be a dictionary with keys `'groups'`, `'leaves'` and `'bytes'` having a numeric value. Their values will be incremented to reflect the number of groups, leaves and bytes, respectively, that have been copied during the operation.

### 4.4.2.3. _f_iterNodes(classname=None)

Returns an iterator yielding all the object nodes hanging from this instance. The nodes are alpha-numerically sorted by its node name. If a classname parameter is supplied, it will only return instances of this class (or subclasses of it).

### 4.4.2.4. _f_listNodes(classname=None)

Returns a list with all the object nodes hanging from this instance. The list is alpha-numerically sorted by node name. If a classname parameter is supplied, it will only return instances of this class (or subclasses of it).

### 4.4.2.5. _f_walkGroups()

Iterate over the list of Groups (not Leaves) hanging from (and including) self. This Group is listed first (pre-order), then each of its child Groups (following an alpha-numerical order) is also traversed, following the same procedure.

### 4.4.2.6. _f_walkNodes(classname=None, recursive=True)

Iterate over the nodes in the `Group` instance. It takes two parameters:

classname

  (String) If supplied, only instances of this class are returned.

recursive

  (Integer) If false, only children hanging immediately after the group are returned. If true, a recursion over all the groups hanging from it is performed.

Example of use:

    	      # Recursively print all the arrays hanging from '/'
    	      print "Arrays the object tree '/':"
    	      for array in h5file.root._f_walkNodes("Array", recursive=1):
    	          print array

### 4.4.2.7. _f_close()

Close this node in the tree.

This method has the behavior described in `Node._f_close()` (see [here]). It should be noted that this operation disables access to nodes descending from this group. Therefore, if you want to explicitly close them, you will need to walk the nodes hanging from this group before closing it.

### 4.4.2.8. _f_copyChildren(dstgroup, overwrite=False, recursive=False, **kwargs)

Copy the children of this group into another group.

Children hanging directly from this group are copied into `dstgroup`, which can be a `Group` (see 4.4) object or its pathname in string form.

The operation will fail with a `NodeError` if there is a child node in the destination group with the same name as one of the copied children from this one, unless `overwrite` is true; in this case, the former child node is recursively removed before copying the later.

By default, nodes descending from children groups of this node are not copied. If the `recursive` argument is true, all descendant nodes of this node are recursively copied.

Additional keyword arguments may be passed to customize the copying process. For instance, title and filters may be changed, user attributes may be or may not be copied, data may be sub-sampled, stats may be collected, etc. Arguments unknown to nodes are simply ignored. Check the documentation for copying operations of nodes to see which options they support.

## 4.4.3. Group special methods

Following are described the methods that automatically trigger actions when a `Group` instance is accessed in a special way.

### 4.4.3.1. __setattr__(name, value)

Set a Python attribute called `name` with the given `value`.

This method stores an ordinary Python attribute in the object. It does not store new children nodes under this group; for that, use the `File.create*()` methods (see 4.2). It does neither store a PyTables node attribute; for that, use `File.setNodeAttr()` (see [here]), `Node._f_setAttr()` (see [here]) or `Node._v_attrs` (see [here]).

If there is already a child node with the same `name`, a `NaturalNameWarning` will be issued and the child node will not be accessible via natural naming nor `getattr()`. It will still be available via `File.getNode()` (see [here]), `Group._f_getChild()` (see [here]) and children dictionaries in the group (if visible).

### 4.4.3.2. __getattr__(name)

Get a Python attribute or child node called `name`.

If the object has a Python attribute called `name`, its value is returned. Else, if the node has a child node called `name`, it is returned. Else, an `AttributeError` is raised.

### 4.4.3.3. __delattr__(name)

Delete a Python attribute called `name`.

This method deletes an ordinary Python attribute from the object. It does not remove children nodes from this group; for that, use `File.removeNode()` (see [here]) or `Node._f_remove()` (see [here]). It does neither delete a PyTables node attribute; for that, use `File.delNodeAttr()` (see [here]), `Node._f_delAttr()` (see [here]) or `Node._v_attrs` (see [here]).

If there were an attribute and a child node with the same `name`, the child node will be made accessible again via natural naming.

### 4.4.3.4. __contains__(name)

Is there a child with that name?

Returns `True` if the group has a child node (visible or hidden) with the given name (a string), `False` otherwise.

### 4.4.3.5. __iter__()

Iterate over the children on the group instance. However, this does not accept parameters. This iterator is not recursive.

Example of use:

    	      # Non-recursively list all the nodes hanging from '/detector'
    	      print "Nodes in '/detector' group:"
    	      for node in h5file.root.detector:
    	          print node

### 4.4.3.6. __str__()

Prints a short description of the `Group` object.

Example of use:

    >>> f=tables.openFile("data/test.h5")
    >>> print f.root.group0
    /group0 (Group) 'First Group'
    >>>

### 4.4.3.7. __repr__()

Prints a detailed description of the `Group` object.

Example of use:

    >>> f=tables.openFile("data/test.h5")
    >>> f.root.group0
    /group0 (Group) 'First Group'
      children := ['tuple1' (Table), 'group1' (Group)]
    >>>

Prev | Home | Next
The Node class | Up | The Leaf class