[h5py] 44/455: Moved all public functions to automatic exception handling
Ghislain Vaillant
ghisvail-guest at moszumanska.debian.org
Thu Jul 2 18:19:16 UTC 2015
This is an automated email from the git hooks/post-receive script.
ghisvail-guest pushed a commit to annotated tag 1.3.0
in repository h5py.
commit debbfb92131f5a97951e33e0daa0ce94d73b48bb
Author: andrewcollette <andrew.collette at gmail.com>
Date: Tue Jun 10 00:10:46 2008 +0000
Moved all public functions to automatic exception handling
---
h5py/__init__.py | 2 +-
h5py/errors.py | 56 --------
h5py/h5.pyx | 2 +
h5py/h5a.pyx | 100 ++++++---------
h5py/h5d.pyx | 138 +++++++-------------
h5py/h5e.pxd | 2 +-
h5py/h5e.pyx | 85 +++++++------
h5py/h5f.pxd | 32 ++---
h5py/h5f.pyx | 115 ++++-------------
h5py/h5g.pxd | 32 ++---
h5py/h5g.pyx | 146 +++++++--------------
h5py/h5i.pxd | 19 ++-
h5py/h5i.pyx | 50 +++-----
h5py/h5p.pxd | 100 +++++++--------
h5py/h5p.pyx | 172 +++++++------------------
h5py/h5r.pxd | 8 +-
h5py/h5r.pyx | 29 +----
h5py/h5s.pxd | 56 ++++----
h5py/h5s.pyx | 339 ++++++++++++++-----------------------------------
h5py/h5t.pxd | 130 ++++++++++---------
h5py/h5t.pyx | 326 ++++++++++++++++-------------------------------
h5py/h5z.pxd | 4 +-
h5py/h5z.pyx | 12 +-
h5py/python.pxd | 2 +-
h5py/tests/__init__.py | 10 +-
h5py/tests/test_h5a.py | 34 ++---
h5py/utils.pxd | 14 +-
h5py/utils.pyx | 18 +++
h5py/utils_low.c | 48 ++++---
h5py/utils_low.h | 8 +-
setup.py | 2 +-
31 files changed, 766 insertions(+), 1325 deletions(-)
diff --git a/h5py/__init__.py b/h5py/__init__.py
index 1ac9ca4..c6a3a69 100644
--- a/h5py/__init__.py
+++ b/h5py/__init__.py
@@ -22,7 +22,7 @@ __doc__ = \
See the docstring for the "version" module for a longer introduction.
"""
-import h5, h5f, h5g, h5s, h5t, h5d, h5a, h5p, h5z, h5i, highlevel, errors
+import h5, h5f, h5g, h5s, h5t, h5d, h5a, h5p, h5z, h5i#, highlevel, errors
import tests
import version
diff --git a/h5py/errors.py b/h5py/errors.py
deleted file mode 100644
index f7bc2eb..0000000
--- a/h5py/errors.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#+
-#
-# This file is part of h5py, a low-level Python interface to the HDF5 library.
-#
-# Copyright (C) 2008 Andrew Collette
-# http://h5py.alfven.org
-# License: BSD (See LICENSE.txt for full license)
-#
-# $Date$
-#
-#-
-
-class H5Error(StandardError):
- pass
-
-class ConversionError(H5Error):
- pass
-
-class H5LibraryError(H5Error):
- pass
-
-class FileError(H5LibraryError):
- pass
-
-class GroupError(H5LibraryError):
- pass
-
-class DataspaceError(H5LibraryError):
- pass
-
-class DatatypeError(H5LibraryError):
- pass
-
-class DatasetError(H5LibraryError):
- pass
-
-class PropertyError(H5LibraryError):
- pass
-
-class H5AttributeError(H5LibraryError):
- pass
-
-class FilterError(H5LibraryError):
- pass
-
-class H5TypeError(H5LibraryError):
- pass
-
-class IdentifierError(H5LibraryError):
- pass
-
-class H5ReferenceError(H5LibraryError):
- pass
-
-
-
diff --git a/h5py/h5.pyx b/h5py/h5.pyx
index e71ef8d..aea1e3c 100644
--- a/h5py/h5.pyx
+++ b/h5py/h5.pyx
@@ -24,6 +24,7 @@
"""
from h5e cimport _enable_exceptions
+from numpy cimport import_array
# === Library init ============================================================
@@ -34,6 +35,7 @@ cdef int import_hdf5() except -1:
return 0
import_hdf5()
+import_array()
# === API =====================================================================
diff --git a/h5py/h5a.pyx b/h5py/h5a.pyx
index e31237c..6aba468 100644
--- a/h5py/h5a.pyx
+++ b/h5py/h5a.pyx
@@ -17,22 +17,19 @@
"""
# Pyrex compile-time imports
-from defs_c cimport malloc, free
from h5 cimport herr_t, hid_t
from h5p cimport H5P_DEFAULT
-from h5t cimport H5Tclose
+from h5t cimport PY_H5Tclose
from h5s cimport H5Sclose
-from numpy cimport ndarray, import_array, PyArray_DATA
-from utils cimport check_numpy_read, check_numpy_write
-from h5e cimport err_c, pause_errors, resume_errors
+
+from numpy cimport ndarray, PyArray_DATA
+from utils cimport check_numpy_read, check_numpy_write, \
+ emalloc, efree
# Runtime imports
import h5
import h5t
import h5s
-from errors import H5AttributeError
-
-import_array()
# === General attribute operations ============================================
@@ -59,20 +56,12 @@ def open_name(hid_t loc_id, char* name):
"""
return H5Aopen_name(loc_id, name)
-def close(hid_t attr_id, int force=0):
- """ (INT attr_id, BOOL force=0)
+def close(hid_t attr_id):
+ """ (INT attr_id)
- Close this attribute and release resources. If "force" is True,
- ignore any errors encountered when closing (e.g. when calling in
- a finally clause or destructor).
+ Close this attribute and release resources.
"""
- cdef err_c cookie
- if force:
- cookie = pause_errors()
- H5Aclose(attr_id)
- resume_errors(cookie)
- else:
- H5Aclose(attr_id)
+ H5Aclose(attr_id)
def delete(hid_t loc_id, char* name):
""" (INT loc_id, STRING name)
@@ -95,9 +84,7 @@ def read(hid_t attr_id, ndarray arr_obj):
"""
cdef hid_t mtype_id
cdef hid_t space_id
- cdef herr_t retval
cdef int array_ok
- cdef err_c cookie
mtype_id = 0
space_id = 0
@@ -111,10 +98,10 @@ def read(hid_t attr_id, ndarray arr_obj):
H5Aread(attr_id, mtype_id, PyArray_DATA(arr_obj))
finally:
- cookie = pause_errors()
- H5Tclose(mtype_id)
- H5Sclose(space_id)
- resume_errors(cookie)
+ if mtype_id:
+ PY_H5Tclose(mtype_id)
+ if space_id:
+ H5Sclose(space_id)
def write(hid_t attr_id, ndarray arr_obj):
""" (INT attr_id, NDARRAY arr_obj)
@@ -129,9 +116,7 @@ def write(hid_t attr_id, ndarray arr_obj):
cdef hid_t mtype_id
cdef hid_t space_id
- cdef herr_t retval
cdef int array_ok
- cdef err_c cookie
mtype_id = 0
space_id = 0
@@ -145,10 +130,10 @@ def write(hid_t attr_id, ndarray arr_obj):
H5Awrite(attr_id, mtype_id, PyArray_DATA(arr_obj))
finally:
- cookie = pause_errors()
- H5Tclose(mtype_id)
- H5Sclose(space_id)
- resume_errors(cookie)
+ if mtype_id:
+ PY_H5Tclose(mtype_id)
+ if space_id:
+ H5Sclose(space_id)
# === Attribute inspection ====================================================
@@ -170,11 +155,11 @@ def get_name(hid_t attr_id):
try:
blen = H5Aget_name(attr_id, 0, NULL)
- buf = <char*>malloc(sizeof(char)*blen+1)
+ buf = <char*>emalloc(sizeof(char)*blen+1)
blen = H5Aget_name(attr_id, blen+1, buf)
strout = buf
finally:
- free(buf)
+ efree(buf)
return strout
@@ -263,7 +248,6 @@ def py_create(hid_t loc_id, char* name, object dtype_in, object shape):
cdef hid_t sid
cdef hid_t type_id
cdef hid_t aid
- cdef err_c cookie
sid = 0
type_id = 0
@@ -271,15 +255,14 @@ def py_create(hid_t loc_id, char* name, object dtype_in, object shape):
sid = h5s.create_simple(shape)
type_id = h5t.py_dtype_to_h5t(dtype_in)
- aid = create(loc_id, name, type_id, sid)
+ return create(loc_id, name, type_id, sid)
+
finally:
- cookie = pause_errors()
if sid:
H5Sclose(sid)
if type_id:
- H5Tclose(type_id)
- resume_errors(cookie)
- return aid
+ PY_H5Tclose(type_id)
+
def py_shape(hid_t attr_id):
""" (INT attr_id) => TUPLE shape
@@ -287,18 +270,15 @@ def py_shape(hid_t attr_id):
Retrieve the dataspace of this attribute, as a Numpy-style shape tuple.
"""
cdef hid_t sid
- cdef err_c cookie
sid = 0
try:
sid = H5Aget_space(attr_id)
- tpl = h5s.get_simple_extent_dims(sid)
+ return h5s.get_simple_extent_dims(sid)
+
finally:
- cookie = pause_errors()
if sid:
H5Sclose(sid)
- resume_errors(cookie)
- return tpl
def py_dtype(hid_t attr_id):
""" (INT attr_id) => DTYPE numpy_dtype
@@ -313,11 +293,10 @@ def py_dtype(hid_t attr_id):
try:
type_id = get_type(attr_id)
- dtype_out = h5t.py_h5t_to_dtype(type_id)
+ return h5t.py_h5t_to_dtype(type_id)
finally:
if type_id:
- H5Tclose(type_id)
- return dtype_out
+ PY_H5Tclose(type_id)
def py_get(hid_t parent_id, char* name):
""" (INT parent_id, STRING name)
@@ -326,16 +305,17 @@ def py_get(hid_t parent_id, char* name):
A 0-dimensional array is returned in the case of a scalar attribute.
"""
cdef hid_t attr_id
- attr_id = open_name(parent_id, name)
+ attr_id = H5Aopen_name(parent_id, name)
try:
space = py_shape(attr_id)
dtype = py_dtype(attr_id)
arr = ndarray(space, dtype=dtype)
read(attr_id, arr)
+ return arr
+
finally:
H5Aclose(attr_id)
- return arr
def py_set(hid_t parent_id, char* name, ndarray arr):
""" (INT parent_id, STRING name, NDARRAY arr)
@@ -346,7 +326,6 @@ def py_set(hid_t parent_id, char* name, ndarray arr):
attribute of the same name already exists.
"""
cdef hid_t attr_id
- attr_id = 0
attr_id = py_create(parent_id, name, arr.dtype, arr.shape)
try:
write(attr_id, arr)
@@ -364,21 +343,14 @@ def py_exists(hid_t parent_id, char* name):
py_set().
"""
cdef hid_t attr_id
- cdef err_c cookie
- attr_id = 0
+ try:
+ attr_id = H5Aopen_name(parent_id, name)
+ except:
+ return False
- cookie = pause_errors()
- attr_id = H5Aopen_name(parent_id, name)
- resume_errors(cookie)
-
- if attr_id < 0:
- response = False
- else:
- response = True
- H5Aclose(attr_id)
-
- return response
+ H5Aclose(attr_id)
+ return True
diff --git a/h5py/h5d.pyx b/h5py/h5d.pyx
index 4d0d983..dfdc988 100644
--- a/h5py/h5d.pyx
+++ b/h5py/h5d.pyx
@@ -23,23 +23,21 @@
"""
# Pyrex compile-time imports
-from defs_c cimport malloc, free
from h5 cimport herr_t, hid_t, size_t, hsize_t, htri_t, haddr_t, HADDR_UNDEF
from h5s cimport H5Sclose, H5S_ALL, H5S_UNLIMITED, H5S_SCALAR, H5S_SIMPLE
-from h5t cimport H5Tclose
-from h5p cimport H5P_DEFAULT
-from numpy cimport ndarray, import_array, PyArray_DATA
-from utils cimport check_numpy_read, check_numpy_write, tuple_to_dims
+from h5t cimport PY_H5Tclose
+from h5p cimport H5P_DEFAULT, H5Pclose
+from numpy cimport ndarray, PyArray_DATA
+from utils cimport check_numpy_read, check_numpy_write, \
+ convert_tuple, \
+ emalloc, efree
# Runtime imports
import h5
from h5 import DDict
-from errors import DatasetError
import h5t
import h5s
-import_array()
-
# === Public constants and data structures ====================================
COMPACT = H5D_COMPACT
@@ -75,30 +73,19 @@ def create(int loc_id, char* name, hid_t type_id, hid_t space_id, hid_t plist=H5
For a friendlier version of this function, try py_create()
"""
- cdef hid_t dataset_id
- dataset_id = H5Dcreate(loc_id, name, type_id, space_id, plist)
- if dataset_id < 0:
- raise DatasetError('Failed to create dataset "%s" under %d' % (name, loc_id))
- return dataset_id
+ return H5Dcreate(loc_id, name, type_id, space_id, plist)
def open(hid_t loc_id, char* name):
""" (INT loc_id, STRING name) => INT dataset_id
Open an existing dataset attached to a group or file object, by name.
"""
- cdef hid_t dset_id
- dset_id = H5Dopen(loc_id, name)
- if dset_id < 0:
- raise DatasetError('Failed to open dataset "%s" under %d' % (name, loc_id))
- return dset_id
+ return H5Dopen(loc_id, name)
def close(hid_t dset_id):
""" (INT dset_id)
"""
- cdef herr_t retval
- retval = H5Dclose(dset_id)
- if retval < 0:
- raise DatasetError("Failed to close dataset %d" % dset_id)
+ H5Dclose(dset_id)
# === Dataset I/O =============================================================
@@ -133,12 +120,11 @@ def read(hid_t dset_id, hid_t mspace_id, hid_t fspace_id, ndarray arr_obj, hid_t
if array_ok <= 0:
raise ValueError("Numpy array is not set up correctly.")
- retval = H5Dread(dset_id, mtype_id, mspace_id, fspace_id, plist, PyArray_DATA(arr_obj))
- if retval < 0:
- raise DatasetError("Error reading from dataset %d" % dset_id)
+ H5Dread(dset_id, mtype_id, mspace_id, fspace_id, plist, PyArray_DATA(arr_obj))
+
finally:
if mtype_id != 0:
- H5Tclose(mtype_id)
+ PY_H5Tclose(mtype_id)
def write(hid_t dset_id, hid_t mspace_id, hid_t fspace_id, ndarray arr_obj, hid_t plist=H5P_DEFAULT):
""" ( INT dset_id, INT mspace_id, INT fspace_id, NDARRAY arr_obj,
@@ -163,12 +149,11 @@ def write(hid_t dset_id, hid_t mspace_id, hid_t fspace_id, ndarray arr_obj, hid_
if array_ok <= 0:
raise ValueError("Numpy array is not set up correctly.")
- retval = H5Dwrite(dset_id, mtype_id, mspace_id, fspace_id, plist, PyArray_DATA(arr_obj))
- if retval < 0:
- raise DatasetError("Error writing to dataset %d" % dset_id)
+ H5Dwrite(dset_id, mtype_id, mspace_id, fspace_id, plist, PyArray_DATA(arr_obj))
+
finally:
if mtype_id:
- H5Tclose(mtype_id)
+ PY_H5Tclose(mtype_id)
def extend(hid_t dset_id, object shape):
""" (INT dset_id, TUPLE shape)
@@ -186,23 +171,18 @@ def extend(hid_t dset_id, object shape):
dims = NULL
try:
- space_id = get_space(dset_id)
- rank = h5s.get_simple_extent_ndims(space_id)
- if len(shape) != rank:
- raise ValueError("Tuple rank must match dataspace rank %d; got %s" % (rank, repr(shape)))
+ space_id = H5Dget_space(dset_id)
+ rank = H5Sget_simple_extent_ndims(space_id)
- dims = tuple_to_dims(shape)
- if dims == NULL:
- raise ValueError("Invalid tuple supplied: %s" % repr(shape))
+ require_tuple(shape, 0, rank, "shape")
+ dims = <hsize_t*>emalloc(sizeof(hsize_t)*rank)
+ convert_tuple(shape, dims, rank)
+ H5Dextend(dset_id, dims)
- retval = H5Dextend(dset_id, dims)
- if retval < 0:
- raise DatasetError("Failed to extend dataset %d" % dset_id)
finally:
- if space_id != 0:
+ efree(dims)
+ if space_id:
H5Sclose(space_id)
- if dims != NULL:
- free(dims)
# === Dataset inspection ======================================================
@@ -212,11 +192,7 @@ def get_space(hid_t dset_id):
Create and return a new copy of the dataspace for this dataset. You're
responsible for closing it.
"""
- cdef hid_t space_id
- space_id = H5Dget_space(dset_id)
- if space_id < 0:
- raise DatasetError("Error retrieving space of dataset %d" % dset_id)
- return space_id
+ return H5Dget_space(dset_id)
def get_space_status(hid_t dset_id):
""" (INT dset_id) => INT space_status_code
@@ -225,10 +201,7 @@ def get_space_status(hid_t dset_id):
one of SPACE_STATUS_*.
"""
cdef H5D_space_status_t status
- cdef herr_t retval
- retval = H5Dget_space_status(dset_id, &status)
- if retval < 0:
- raise DatasetError("Error determining allocation status of dataset %d" % dset_id)
+ H5Dget_space_status(dset_id, &status)
return <int>status
def get_type(hid_t dset_id):
@@ -237,11 +210,7 @@ def get_type(hid_t dset_id):
Create and return a new copy of the datatype for this dataset.You're
responsible for closing it.
"""
- cdef hid_t type_id
- type_id = H5Dget_type(dset_id)
- if type_id < 0:
- raise DatasetError("Error retrieving type of dataset %d" % dset_id)
- return type_id
+ return H5Dget_type(dset_id)
def get_create_plist(hid_t dset_id):
""" (INT dset_id) => INT property_list_id
@@ -249,22 +218,14 @@ def get_create_plist(hid_t dset_id):
Create a new copy of the dataset creation property list used when this
dataset was created. You're responsible for closing it.
"""
- cdef hid_t plist
- plist = H5Dget_create_plist(dset_id)
- if plist < 0:
- raise DatasetError("Error retrieving creation property list for dataset %d" % dset_id)
- return plist
+ return H5Dget_create_plist(dset_id)
def get_offset(hid_t dset_id):
""" (INT dset_id) => LONG offset
Get the offset of this dataset in the file, in bytes.
"""
- cdef haddr_t retval
- retval = H5Dget_offset(dset_id)
- if retval == HADDR_UNDEF:
- raise DatasetError("Error determining file offset of dataset %d" % dset_id)
- return retval
+ return H5Dget_offset(dset_id)
def get_storage_size(hid_t dset_id):
""" (INT dset_id) => LONG storage_size
@@ -273,9 +234,7 @@ def get_storage_size(hid_t dset_id):
only counts the space which has actually been allocated; it may even
be zero. Because of this, this function will never raise an exception.
"""
- cdef hsize_t retval
- retval = H5Dget_storage_size(dset_id)
- return retval
+ return H5Dget_storage_size(dset_id)
# === Python extensions =======================================================
@@ -349,7 +308,7 @@ def py_create(hid_t parent_id, char* name, object data=None, object dtype=None,
if space_id:
H5Sclose(space_id)
if type_id:
- H5Tclose(type_id)
+ PY_H5Tclose(type_id)
if plist:
H5Pclose(plist)
@@ -435,12 +394,12 @@ def py_read_slab(hid_t ds_id, object start, object count,
finally:
# ignore return values on cleanup
- if mem_space != 0:
+ if mem_space:
H5Sclose(mem_space)
- if file_space != 0:
+ if file_space:
H5Sclose(file_space)
- if type_id != 0:
- H5Tclose(type_id)
+ if type_id:
+ PY_H5Tclose(type_id)
return arr
@@ -498,9 +457,9 @@ def py_write_slab(hid_t ds_id, ndarray arr, object start, object stride=None):
finally:
# ignore return values on cleanup
- if mem_space != 0:
+ if mem_space:
H5Sclose(mem_space)
- if file_space != 0:
+ if file_space:
H5Sclose(file_space)
def py_shape(hid_t dset_id):
@@ -548,7 +507,7 @@ def py_dtype(hid_t dset_id):
dtype_out = h5t.py_h5t_to_dtype(type_id)
finally:
if type_id:
- H5Tclose(type_id)
+ PY_H5Tclose(type_id)
return dtype_out
def py_patch(hid_t ds_source, hid_t ds_sink, hid_t transfer_space):
@@ -593,30 +552,25 @@ def py_patch(hid_t ds_source, hid_t ds_sink, hid_t transfer_space):
# out again to the same selection preserves the arrangement of data
# elements. I think this is a reasonable assumption.
- xfer_buf = malloc(npoints*type_size)
+ xfer_buf = emalloc(npoints*type_size)
# Let the HDF5 library do dataspace validation; the worst that can
# happen is that the write will fail after taking a while to read.
- retval = H5Dread(ds_source, source_type, mem_space, transfer_space, H5P_DEFAULT, xfer_buf)
- if retval < 0:
- raise DatasetError("Source read failed.")
-
- retval = H5Dwrite(ds_sink, source_type, mem_space, transfer_space, H5P_DEFAULT, xfer_buf)
- if retval < 0:
- raise DatasetError("Sink write failed.")
+ H5Dread(ds_source, source_type, mem_space, transfer_space, H5P_DEFAULT, xfer_buf)
+ H5Dwrite(ds_sink, source_type, mem_space, transfer_space, H5P_DEFAULT, xfer_buf)
finally:
- if source_space != 0:
+ if source_space:
H5Sclose(source_space)
- if sink_space != 0:
+ if sink_space:
H5Sclose(sink_space)
- if mem_space != 0:
+ if mem_space:
H5Sclose(mem_space)
- if source_type != 0:
- H5Tclose(source_type)
+ if source_type:
+ PY_H5Tclose(source_type)
if xfer_buf != NULL:
- free(xfer_buf)
+ efree(xfer_buf)
PY_LAYOUT = DDict({ H5D_COMPACT: 'COMPACT LAYOUT',
H5D_CONTIGUOUS: 'CONTIGUOUS LAYOUT',
diff --git a/h5py/h5e.pxd b/h5py/h5e.pxd
index 3d265f6..1c538cb 100644
--- a/h5py/h5e.pxd
+++ b/h5py/h5e.pxd
@@ -206,7 +206,7 @@ ctypedef H5E_auto_t err_c
cdef int _enable_exceptions() except -1
cdef int _disable_exceptions() except -1
-cdef err_c pause_errors() except NULL
+cdef err_c pause_errors() except? NULL
cdef int resume_errors(err_c cookie) except -1
diff --git a/h5py/h5e.pyx b/h5py/h5e.pyx
index 2f12e9a..d315f82 100644
--- a/h5py/h5e.pyx
+++ b/h5py/h5e.pyx
@@ -10,22 +10,26 @@
#
#-
-from python cimport PyExc_Exception, PyErr_SetString
+from python cimport PyErr_SetObject
# === Public exception hierarchy ==============================================
-class H5Error(StandardError):
- """ Base class for internal HDF5 library exceptions
+class H5Error(EnvironmentError):
+ """ Base class for internal HDF5 library exceptions.
+ Subclass of EnvironmentError; errno is computed from the HDF5 major
+ and minor error numbers:
+ 1000*(major number) + minor number
"""
pass
class ConversionError(StandardError):
""" Indicates error on Python side of dtype transformation.
+ Subclass of StandardError, as this is not a library problem.
"""
pass
class FileError(H5Error):
- """ HDF5 file I/0 error
+ """ HDF5 logical file error (H5E_FILE)
"""
pass
@@ -33,21 +37,33 @@ class GroupError(H5Error):
pass
class DataspaceError(H5Error):
+ """ H5E_DATASPACE
+ """
pass
class DatatypeError(H5Error):
+ """ H5E_DATATYPE
+ """
pass
class DatasetError(H5Error):
+ """ H5E_DATASET
+ """
pass
class PropertyError(H5Error):
+ """ H5E_PLIST
+ """
pass
class H5AttributeError(H5Error):
+ """ H5E_ATTR
+ """
pass
class FilterError(H5Error):
+ """ H5E_PLINE
+ """
pass
class IdentifierError(H5Error):
@@ -75,6 +91,7 @@ cdef class H5ErrorStackElement:
return '%2d:%2d "%s" at %s (%s: %s)' % (self.maj_num, self.min_num,
self.desc, self.func_name, H5Eget_major(<H5E_major_t>self.maj_num),
H5Eget_minor(<H5E_minor_t>self.min_num) )
+
cdef herr_t walk_cb(int n, H5E_error_t *err_desc, void* stack_in):
# Callback function to extract elements from the HDF5 error stack
@@ -116,13 +133,31 @@ def get_error_string():
if stacklen > 1:
msg = msg + "\nHDF5 Error Stack:"
for i from 0<=i<stacklen:
- msg = msg + '\n' + str(stack[i])
- #el = stack[i]
- #msg = msg + '\n %d: "%s" at %s' % \
- # (i, el.desc.capitalize(), el.func_name)
+ #msg = msg + '\n' + str(stack[i])
+ el = stack[i]
+ msg = msg + '\n %d: "%s" at %s' % \
+ (i, el.desc.capitalize(), el.func_name)
return msg
+def get_major(int error):
+ """ (INT error) => STRING description
+ """
+ return H5E_get_major(<H5E_major_t>error)
+
+def get_minor(int error):
+ """ (INT error) => STRING description
+ """
+ return H5E_get_minor(<H5E_minor_t>error)
+
+def get_error(int error):
+ """ (INT errno) => STRING description
+ """
+ cdef int mj
+ cdef int mn
+ mn = error % 1000
+ mj = (error-mn)/1000
+ return "%s: %s" % (H5E_get_major(<H5E_major_t>mj), H5E_get_minor(<H5E_minor_t>mn))
# === Automatic exception API =================================================
@@ -158,8 +193,7 @@ cdef herr_t err_callback(void* client_data):
# Map function argument exceptions to native Python exceptions.
# H5E_BADTYPE does not raise TypeError as this is too easily confused
# with the results of Pyrex auto-validation.
- elif mj == H5E_ARGS and (mn == H5E_BADRANGE or mn == H5E_BADVALUE \
- or mn == H5E_BADTYPE):
+ elif mj == H5E_ARGS:
exc = ValueError
# Major errors which map to new h5e exception classes
@@ -185,7 +219,10 @@ cdef herr_t err_callback(void* client_data):
exc = H5Error
msg = get_error_string()
- PyErr_SetString(exc, msg)
+ if issubclass(exc, EnvironmentError):
+ PyErr_SetObject(exc, (1000*mj + mn, msg))
+ else:
+ PyErr_SetObject(exc, msg)
return 1
@@ -201,7 +238,7 @@ cdef int _disable_exceptions() except -1:
raise RuntimeError("Failed to unregister HDF5 exception callback.")
return 0
-cdef err_c pause_errors() except NULL:
+cdef err_c pause_errors() except? NULL:
# Temporarily disable automatic exception handling, and return a cookie
# which can later be used to re-enable it.
cdef err_c cookie
@@ -227,30 +264,6 @@ cdef int resume_errors(err_c cookie) except -1:
return 0
-# --- temporary test functions ---
-
-cdef extern from "hdf5.h":
- htri_t H5Pexist( hid_t id, char *name) except *
- herr_t H5Tclose(hid_t type_id ) except *
- hid_t H5T_STD_I8LE
-
-def test_error():
- H5Pexist(-1, "foobar")
-
-def test_2():
- H5Tclose(H5T_STD_I8LE)
-
-cdef void ctest3() except *:
- PyErr_SetString(Foobar, "foo")
-
-def test_3():
- ctest3()
-
-
-
-
-
-
diff --git a/h5py/h5f.pxd b/h5py/h5f.pxd
index f405a5f..58b6547 100644
--- a/h5py/h5f.pxd
+++ b/h5py/h5f.pxd
@@ -45,22 +45,22 @@ cdef extern from "hdf5.h":
# --- File operations -------------------------------------------------------
hid_t H5Fcreate(char *filename, unsigned int flags,
- hid_t create_plist, hid_t access_plist)
- hid_t H5Fopen(char *name, unsigned flags, hid_t access_id)
- herr_t H5Fclose (hid_t file_id)
- htri_t H5Fis_hdf5(char *name)
- herr_t H5Fflush(hid_t object_id, H5F_scope_t scope)
-
- hid_t H5Freopen(hid_t file_id)
- herr_t H5Fmount(hid_t loc_id, char *name, hid_t child_id, hid_t plist_id)
- herr_t H5Funmount(hid_t loc_id, char *name)
- herr_t H5Fget_filesize(hid_t file_id, hsize_t *size)
- hid_t H5Fget_create_plist(hid_t file_id )
- hid_t H5Fget_access_plist(hid_t file_id)
- hssize_t H5Fget_freespace(hid_t file_id)
- ssize_t H5Fget_name(hid_t obj_id, char *name, size_t size)
- int H5Fget_obj_count(hid_t file_id, unsigned int types)
- int H5Fget_obj_ids(hid_t file_id, unsigned int types, int max_objs, hid_t *obj_id_list)
+ hid_t create_plist, hid_t access_plist) except *
+ hid_t H5Fopen(char *name, unsigned flags, hid_t access_id) except *
+ herr_t H5Fclose (hid_t file_id) except *
+ htri_t H5Fis_hdf5(char *name) except *
+ herr_t H5Fflush(hid_t object_id, H5F_scope_t scope) except *
+
+ hid_t H5Freopen(hid_t file_id) except *
+ herr_t H5Fmount(hid_t loc_id, char *name, hid_t child_id, hid_t plist_id) except *
+ herr_t H5Funmount(hid_t loc_id, char *name) except *
+ herr_t H5Fget_filesize(hid_t file_id, hsize_t *size) except *
+ hid_t H5Fget_create_plist(hid_t file_id ) except *
+ hid_t H5Fget_access_plist(hid_t file_id) except *
+ hssize_t H5Fget_freespace(hid_t file_id) except *
+ ssize_t H5Fget_name(hid_t obj_id, char *name, size_t size) except *
+ int H5Fget_obj_count(hid_t file_id, unsigned int types) except *
+ int H5Fget_obj_ids(hid_t file_id, unsigned int types, int max_objs, hid_t *obj_id_list) except *
diff --git a/h5py/h5f.pyx b/h5py/h5f.pyx
index 71099c8..cc0d4ec 100644
--- a/h5py/h5f.pyx
+++ b/h5py/h5f.pyx
@@ -12,19 +12,16 @@
"""
Low-level operations on HDF5 file objects.
-
- Functions in this module raise errors.FileError.
"""
# Pyrex compile-time imports
-from defs_c cimport malloc, free
from h5 cimport herr_t, hid_t, htri_t, hssize_t
from h5p cimport H5P_DEFAULT
+from utils cimport emalloc, efree
# Runtime imports
import h5
from h5 import DDict
-from errors import FileError
# === Public constants and data structures ====================================
@@ -58,20 +55,12 @@ def open(char* name, unsigned int flags=H5F_ACC_RDWR, hid_t access_id=H5P_DEFAUL
Open an existing HDF5 file. Keyword "flags" may be ACC_RWDR or
ACC_RDONLY. Keyword "access_id" may be a file access property list.
"""
- cdef hid_t retval
- retval = H5Fopen(name, flags, access_id)
-
- if retval < 0:
- raise FileError("Failed to open file '%s'" % name)
- return retval
+ return H5Fopen(name, flags, access_id)
def close(hid_t file_id):
""" (INT file_id)
"""
- cdef herr_t retval
- retval = H5Fclose(file_id)
- if retval < 0:
- raise FileError("Failed to close file id %d" % file_id)
+ H5Fclose(file_id)
def create(char* name, int flags=H5F_ACC_TRUNC, hid_t create_id=H5P_DEFAULT, hid_t access_id=H5P_DEFAULT):
""" (STRING name, INT flags=ACC_TRUNC, INT create_id=H5P_DEFAULT,
@@ -84,12 +73,7 @@ def create(char* name, int flags=H5F_ACC_TRUNC, hid_t create_id=H5P_DEFAULT, hid
Keywords create_id and access_id may be dataset creation and access
property lists, respectively.
"""
- cdef hid_t retval
- retval = H5Fcreate(name, flags, create_id, access_id)
-
- if retval < 0:
- raise FileError('Failed to create file "%s" mode %d' % (name,flags))
- return retval
+ return H5Fcreate(name, flags, create_id, access_id)
def flush(hid_t file_id, int scope=H5F_SCOPE_LOCAL):
""" (INT file_id, INT scope=SCOPE_LOCAL)
@@ -97,11 +81,7 @@ def flush(hid_t file_id, int scope=H5F_SCOPE_LOCAL):
Tell the HDF5 library to flush file buffers to disk. See the HDF5
docs for the meaning of the scope keyword.
"""
- cdef herr_t retval
- retval = H5Fflush(file_id, <H5F_scope_t>scope)
-
- if retval < 0:
- raise FileError("Failed to flush file %d" % file_id)
+ H5Fflush(file_id, <H5F_scope_t>scope)
def is_hdf5(char* name):
""" (STRING name) => BOOL is_hdf5
@@ -109,22 +89,14 @@ def is_hdf5(char* name):
Determine if a given file is an HDF5 file. Note this raises an
exception if the file doesn't exist.
"""
- cdef htri_t retval
- retval = H5Fis_hdf5(name)
- if retval < 0:
- raise FileError("Can't determine status of file '%s'" % name)
- return bool(retval)
+ return bool(H5Fis_hdf5(name))
def reopen(hid_t file_id):
""" (INT file_id) => INT new_file_id
Retrieve another identifier for a file (which must still be open).
"""
- cdef hid_t retval
- retval = H5Freopen(file_id)
- if retval < 0:
- raise FileError("Faile to re-open file %d" % file_id)
- return retval
+ return H5Freopen(file_id)
def mount(hid_t loc_id, char* name, hid_t file_id, hid_t plist_id=H5P_DEFAULT):
""" (INT loc_id, STRING name, INT file_id, INT, plist_id=H5P_DEFAULT)
@@ -132,20 +104,14 @@ def mount(hid_t loc_id, char* name, hid_t file_id, hid_t plist_id=H5P_DEFAULT):
Mount an open file as "name" under group loc_id. If present, plist_id
is a mount property list.
"""
- cdef herr_t retval
- retval = H5Fmount(loc_id, name, file_id, plist_id)
- if retval < 0:
- raise FileError('Failed to mount file %s as "%s" under group %d' % (file_id, name, loc_id))
+ H5Fmount(loc_id, name, file_id, plist_id)
def unmount(hid_t loc_id, char* name):
""" (INT loc_id, STRING name)
Unmount a file, mounted as "name" under group loc_id.
"""
- cdef herr_t retval
- retval = H5Funmount(loc_id, name)
- if retval < 0:
- raise FileError('Failed to unmount "%s" under group %d' % (name, loc_id))
+ H5Funmount(loc_id, name)
# === File inspection =========================================================
@@ -154,11 +120,8 @@ def get_filesize(hid_t file_id):
Determine the total size of the HDF5 file, including the user block.
"""
- cdef herr_t retval
cdef hsize_t size
- retval = H5Fget_filesize(file_id, &size)
- if retval < 0:
- raise FileError("Can't determine size of file %d" % file_id)
+ H5Fget_filesize(file_id, &size)
return size
def get_create_plist(hid_t file_id):
@@ -166,22 +129,14 @@ def get_create_plist(hid_t file_id):
Retrieve a copy of the property list used to create this file.
"""
- cdef hid_t retval
- retval = H5Fget_create_plist(file_id)
- if retval < 0:
- raise FileError("Can't retrieve creation property list for file %d" % file_id)
- return retval
+ return H5Fget_create_plist(file_id)
def get_access_plist(hid_t file_id):
""" (INT file_id) => INT plist_id
Retrieve a copy of the property list which manages access to this file.
"""
- cdef hid_t retval
- retval = H5Fget_access_plist(file_id)
- if retval < 0:
- raise FileError("Can't retrieve access property list for file %d" % file_id)
- return retval
+ return H5Fget_access_plist(file_id)
def get_freespace(hid_t file_id):
""" (INT file_id) => LONG free space
@@ -189,34 +144,25 @@ def get_freespace(hid_t file_id):
Determine the amount of free space in this file. Note that this only
tracks free space until the file is closed.
"""
- cdef hssize_t retval
- retval = H5Fget_freespace(file_id)
- if retval < 0:
- raise FileError("Can't determine free space in file %d" % file_id)
- return retval
+ return H5Fget_freespace(file_id)
def get_name(hid_t obj_id):
""" (INT obj_id) => STRING file_name
Determine the name of the file in which the specified object resides.
"""
- cdef ssize_t retval
+ cdef ssize_t size
cdef char* name
name = NULL
- retval = H5Fget_name(obj_id, NULL, 0)
- if retval < 0:
- raise FileError("Can't determine file name associated with object %d" % obj_id)
-
- name = <char*>malloc(retval+1)
- retval = H5Fget_name(obj_id, name, retval+1)
- if retval < 0:
- free(name)
- raise FileError("Can't determine file name associated with object %d" % obj_id)
-
- pname = name
- free(name)
- return pname
+ size = H5Fget_name(obj_id, NULL, 0)
+ name = <char*>emalloc(sizeof(char)*(retval+1))
+ try:
+ H5Fget_name(obj_id, name, retval+1)
+ pname = name
+ return pname
+ finally:
+ efree(name)
def get_obj_count(hid_t file_id, int types):
""" (INT file_id, INT types) => INT n_objs
@@ -227,11 +173,7 @@ def get_obj_count(hid_t file_id, int types):
types, and OBJ_LOCAL will only match objects opened through this
specific identifier.
"""
- cdef int retval
- retval = H5Fget_obj_count(file_id, types)
- if retval < 0:
- raise FileError("Can't determine number of open identifiers of types %d in file %d" % (types, file_id))
- return retval
+ return H5Fget_obj_count(file_id, types)
def get_obj_ids(hid_t file_id, int types):
""" (INT file_id, INT types) => LIST open_ids
@@ -253,18 +195,15 @@ def get_obj_ids(hid_t file_id, int types):
try:
count = H5Fget_obj_count(file_id, types)
- if count < 0:
- raise FileError("Failed to count open identifiers.")
- obj_list = <hid_t*>malloc(sizeof(hid_t)*count)
- retval = H5Fget_obj_ids(file_id, types, count, obj_list)
- if retval < 0:
- raise FileError("Failed to enumerate open objects of types %d in file %d" % (types, file_id))
+ obj_list = <hid_t*>emalloc(sizeof(hid_t)*count)
+ H5Fget_obj_ids(file_id, types, count, obj_list)
for i from 0<=i<count:
py_obj_list.append(obj_list[i])
+
finally:
- free(obj_list)
+ efree(obj_list)
return py_obj_list
diff --git a/h5py/h5g.pxd b/h5py/h5g.pxd
index df9c0fa..b63c6b8 100644
--- a/h5py/h5g.pxd
+++ b/h5py/h5g.pxd
@@ -41,28 +41,28 @@ cdef extern from "hdf5.h":
#H5O_stat_t ohdr # Object header information. New in HDF5 1.6
# --- Group operations ------------------------------------------------------
- hid_t H5Gcreate(hid_t loc_id, char *name, size_t size_hint )
- hid_t H5Gopen(hid_t loc_id, char *name )
- herr_t H5Gclose(hid_t group_id)
+ hid_t H5Gcreate(hid_t loc_id, char *name, size_t size_hint ) except *
+ hid_t H5Gopen(hid_t loc_id, char *name ) except *
+ herr_t H5Gclose(hid_t group_id) except *
herr_t H5Glink (hid_t file_id, H5G_link_t link_type,
- char *current_name, char *new_name)
+ char *current_name, char *new_name) except *
herr_t H5Glink2( hid_t curr_loc_id, char *current_name,
- H5G_link_t link_type, hid_t new_loc_id, char *new_name )
+ H5G_link_t link_type, hid_t new_loc_id, char *new_name ) except *
- herr_t H5Gunlink (hid_t file_id, char *name)
- herr_t H5Gmove(hid_t loc_id, char *src, char *dst)
+ herr_t H5Gunlink (hid_t file_id, char *name) except *
+ herr_t H5Gmove(hid_t loc_id, char *src, char *dst) except *
herr_t H5Gmove2(hid_t src_loc_id, char *src_name,
- hid_t dst_loc_id, char *dst_name )
- herr_t H5Gget_num_objs(hid_t loc_id, hsize_t* num_obj)
- int H5Gget_objname_by_idx(hid_t loc_id, hsize_t idx, char *name, size_t size )
- int H5Gget_objtype_by_idx(hid_t loc_id, hsize_t idx )
+ hid_t dst_loc_id, char *dst_name ) except *
+ herr_t H5Gget_num_objs(hid_t loc_id, hsize_t* num_obj) except *
+ int H5Gget_objname_by_idx(hid_t loc_id, hsize_t idx, char *name, size_t size ) except *
+ int H5Gget_objtype_by_idx(hid_t loc_id, hsize_t idx ) except *
ctypedef herr_t (*H5G_iterate_t)(hid_t group, char *name, op_data)
- herr_t H5Giterate(hid_t loc_id, char *name, int *idx, H5G_iterate_t operator, operator_data )
- herr_t H5Gget_objinfo(hid_t loc_id, char* name, int follow_link, H5G_stat_t *statbuf)
+ herr_t H5Giterate(hid_t loc_id, char *name, int *idx, H5G_iterate_t operator, operator_data ) except *
+ herr_t H5Gget_objinfo(hid_t loc_id, char* name, int follow_link, H5G_stat_t *statbuf) except *
- herr_t H5Gget_linkval(hid_t loc_id, char *name, size_t size, char *value)
- herr_t H5Gset_comment(hid_t loc_id, char *name, char *comment )
- int H5Gget_comment(hid_t loc_id, char *name, size_t bufsize, char *comment )
+ herr_t H5Gget_linkval(hid_t loc_id, char *name, size_t size, char *value) except *
+ herr_t H5Gset_comment(hid_t loc_id, char *name, char *comment ) except *
+ int H5Gget_comment(hid_t loc_id, char *name, size_t bufsize, char *comment ) except *
diff --git a/h5py/h5g.pyx b/h5py/h5g.pyx
index 009df46..d5848b8 100644
--- a/h5py/h5g.pyx
+++ b/h5py/h5g.pyx
@@ -15,13 +15,13 @@
"""
# Pyrex compile-time imports
-from defs_c cimport malloc, free, time_t
+from defs_c cimport time_t
from h5 cimport herr_t, hid_t, size_t, hsize_t
+from utils cimport emalloc, efree
# Runtime imports
import h5
from h5 import DDict
-from errors import GroupError
# === Public constants and data structures ====================================
@@ -64,21 +64,12 @@ def open(hid_t loc_id, char* name):
Open an existing HDF5 group, attached to some other group.
"""
- cdef herr_t retval
-
- retval = H5Gopen(loc_id, name)
- if retval < 0:
- raise GroupError("Failed to open group %s at %d" % (name, loc_id))
- return retval
+ return H5Gopen(loc_id, name)
def close(hid_t group_id):
""" (INT group_id)
"""
- cdef herr_t retval
-
- retval = H5Gclose(group_id)
- if retval < 0:
- raise GroupError("Can't close group %d" % group_id)
+ H5Gclose(group_id)
def create(hid_t loc_id, char* name, int size_hint=-1):
""" (INT loc_id, STRING name, INT size_hint=-1)
@@ -86,12 +77,7 @@ def create(hid_t loc_id, char* name, int size_hint=-1):
Create a new group named "name", under a parent group identified by
"loc_id". See the HDF5 documentation for the meaning of size_hint.
"""
- cdef herr_t retval
-
- retval = H5Gcreate(loc_id, name, size_hint)
- if retval < 0:
- raise GroupError("Can't create group %s under %d" % (name, loc_id))
- return retval
+ return H5Gcreate(loc_id, name, size_hint)
# === Group member management =================================================
@@ -108,26 +94,17 @@ def link(hid_t loc_id, char* current_name, char* new_name, int link_type=H5G_LIN
Hard links are created by default (link_type=LINK_HARD). To create a
symbolic link, pass in link_type=LINK_SOFT.
"""
- cdef herr_t retval
-
if remote_id < 0:
remote_id = loc_id
- retval = H5Glink2(loc_id, current_name, <H5G_link_t>link_type, remote_id, new_name)
- if retval < 0:
- raise GroupError('Failed to link %d=>"%s" to %d=>"%s"' % (loc_id, current_name, remote_id, new_name))
+ H5Glink2(loc_id, current_name, <H5G_link_t>link_type, remote_id, new_name)
def unlink(hid_t loc_id, char* name):
""" (INT loc_id, STRING name)
Remove a link to an object from the given group.
"""
- cdef herr_t retval
-
- retval = H5Gunlink(loc_id, name)
- if retval < 0:
- raise GroupError("Failed to unlink member '%s' from group %d" % (name, loc_id))
-
+ H5Gunlink(loc_id, name)
def move(hid_t loc_id, char* current_name, char* new_name, hid_t remote_id=-1):
""" (INT loc_id, STRING current_name, STRING new_name, INT new_group_id=-1)
@@ -136,13 +113,10 @@ def move(hid_t loc_id, char* current_name, char* new_name, hid_t remote_id=-1):
current_name. The new name of the link is new_name. You can create
the link in a different group by passing its identifier to remote_id.
"""
- cdef int retval
if remote_id < 0:
remote_id = loc_id
+ H5Gmove2(loc_id, current_name, remote_id, new_name)
- retval = H5Gmove2(loc_id, current_name, remote_id, new_name)
- if retval < 0:
- raise GroupError('Failed to move %d=>"%s" to %d=>"%s"' % (loc_id, current_name, remote_id, new_name))
# === Member inspection =======================================================
@@ -152,12 +126,7 @@ def get_num_objs(hid_t loc_id):
Get the number of objects attached to a given group.
"""
cdef hsize_t size
- cdef herr_t retval
-
- retval = H5Gget_num_objs(loc_id, &size)
- if retval < 0:
- raise GroupError("Group enumeration failed: %d" % loc_id)
-
+ H5Gget_num_objs(loc_id, &size)
return size
def get_objname_by_idx(hid_t loc_id, hsize_t idx):
@@ -165,21 +134,21 @@ def get_objname_by_idx(hid_t loc_id, hsize_t idx):
Get the name of a group member given its zero-based index.
"""
- cdef int retval
+ cdef int size
cdef char* buf
- cdef object pystring
+ buf = NULL
- retval = H5Gget_objname_by_idx(loc_id, idx, NULL, 0)
- if retval < 0:
- raise GroupError("Error accessing element %d of group %d" % (idx, loc_id))
- elif retval == 0:
- return None
- else:
- buf = <char*>malloc(retval+1)
- retval = H5Gget_objname_by_idx(loc_id, idx, buf, retval+1)
+ size = H5Gget_objname_by_idx(loc_id, idx, NULL, 0)
+ if retval <= 0:
+ raise RuntimeError("Failed to raise exception at get_objname_by_idx.")
+
+ buf = <char*>emalloc(sizeof(char)*(retval+1))
+ try:
+ H5Gget_objname_by_idx(loc_id, idx, buf, retval+1)
pystring = buf
- free(buf)
return pystring
+ finally:
+ efree(buf)
def get_objtype_by_idx(hid_t loc_id, hsize_t idx):
""" (INT loc_id, INT idx) => INT object_type_code
@@ -191,13 +160,7 @@ def get_objtype_by_idx(hid_t loc_id, hsize_t idx):
- DATASET
- DATATYPE
"""
- cdef int retval
-
- retval = H5Gget_objtype_by_idx(loc_id, idx)
- if retval < 0:
- raise GroupError("Error accessing element %d of group %d" % (idx, loc_id))
-
- return retval
+ return H5Gget_objtype_by_idx(loc_id, idx)
def get_objinfo(hid_t loc_id, char* name, int follow_link=1):
""" (INT loc_id, STRING name, BOOL follow_link=True)
@@ -209,13 +172,10 @@ def get_objinfo(hid_t loc_id, char* name, int follow_link=1):
and the object is a symbolic link, the information returned describes
its target. Otherwise the information describes the link itself.
"""
- cdef int retval
cdef H5G_stat_t stat
cdef GroupStat statobj
- retval = H5Gget_objinfo(loc_id, name, follow_link, &stat)
- if retval < 0:
- raise GroupError("Can't stat member \"%s\" of group %d" % (name, loc_id))
+ H5Gget_objinfo(loc_id, name, follow_link, &stat)
statobj = GroupStat()
statobj.fileno = (stat.fileno[0], stat.fileno[1])
@@ -229,10 +189,6 @@ def get_objinfo(hid_t loc_id, char* name, int follow_link=1):
cdef herr_t iter_cb_helper(hid_t gid, char *name, object int_tpl):
- cdef object func
- cdef object data
- cdef object outval
-
func = int_tpl[0]
data = int_tpl[1]
exc_list = int_tpl[2]
@@ -285,36 +241,31 @@ def get_linkval(hid_t loc_id, char* name):
Retrieve the value of the given symbolic link.
"""
cdef char* value
- cdef herr_t retval
cdef H5G_stat_t statbuf
value = NULL
- retval = H5Gget_objinfo(loc_id, name, 0, &statbuf)
- if retval < 0:
- raise GroupError('Can\'t stat "%s" under group %d' % (name, loc_id))
+ H5Gget_objinfo(loc_id, name, 0, &statbuf)
if statbuf.type != H5G_LINK:
- raise GroupError('"%s" is not a symbolic link (type is %s)' % (name, PY_NAMES[statbuf.type]))
+ raise ValueError('"%s" is not a symbolic link.' % name)
- value = <char*>malloc(statbuf.linklen+1)
- retval = H5Gget_linkval(loc_id, name, statbuf.linklen+1, value)
- if retval < 0:
- free(value)
- raise GroupError('Failed to determine link value for "%s"' % name)
+ value = <char*>emalloc(sizeof(char)*(statbuf.linklen+1))
+ try:
+ H5Gget_linkval(loc_id, name, statbuf.linklen+1, value)
+ pyvalue = value
+ return pyvalue
+
+ finally:
+ efree(value)
- pvalue = value
- free(value)
- return pvalue
def set_comment(hid_t loc_id, char* name, char* comment):
""" (INT loc_id, STRING name, STRING comment)
Set the comment on a group member.
"""
- cdef herr_t retval
- retval = H5Gset_comment(loc_id, name, comment)
- if retval < 0:
- raise GroupError('Failed to set comment on member "%s" of group %d' % (name, loc_id))
+ H5Gset_comment(loc_id, name, comment)
+
def get_comment(hid_t loc_id, char* name):
""" (INT loc_id, STRING name) => STRING comment
@@ -327,17 +278,15 @@ def get_comment(hid_t loc_id, char* name):
cmnt_len = H5Gget_comment(loc_id, name, 0, NULL)
if cmnt_len < 0:
- raise GroupError('Failed to get comment for member "%s" of group %d' % (name, loc_id))
+ raise RuntimeError("Failed to raise exception at get_comment")
- cmnt = <char*>malloc(cmnt_len+1)
- cmnt_len = H5Gget_comment(loc_id, name, cmnt_len+1, cmnt)
- if cmnt_len < 0:
- free(cmnt)
- raise GroupError('Failed to get comment for member "%s" of group %d' % (name, loc_id))
-
- p_cmnt = cmnt
- free(cmnt)
- return p_cmnt
+ cmnt = <char*>emalloc(sizeof(char)*(cmnt_len+1))
+ try:
+ H5Gget_comment(loc_id, name, cmnt_len+1, cmnt)
+ py_cmnt = cmnt
+ return py_cmnt
+ finally:
+ efree(cmnt)
# === Custom extensions =======================================================
@@ -347,10 +296,9 @@ def py_listnames(hid_t group_id):
Create a Python list of the object names directly attached to a group.
"""
cdef int nitems
- cdef object thelist
cdef int i
- thelist = []
+ namelist = []
nitems = get_num_objs(group_id)
for i from 0 <= i < nitems:
@@ -378,7 +326,7 @@ cdef class _GroupIterator:
nobjs = -1
H5Gget_num_objs(self.gid, &nobjs)
if nobjs != self.nitems:
- raise GroupError("Group length changed during iteration")
+ raise RuntimeError("Group length changed during iteration")
if self.idx >= self.nitems:
raise StopIteration()
name = get_objname_by_idx(self.gid, self.idx)
@@ -404,9 +352,9 @@ def py_exists(hid_t group_id, char* name, int follow_link=1):
is True (default), symbolic links will be dereferenced. Note this
function will not raise GroupError, even if the group ID is bad.
"""
- cdef int retval
- retval = H5Gget_objinfo(group_id, name, follow_link, NULL)
- if retval < 0:
+ try:
+ H5Gget_objinfo(group_id, name, follow_link, NULL)
+ except:
return False
return True
diff --git a/h5py/h5i.pxd b/h5py/h5i.pxd
index 6e337c0..b785229 100644
--- a/h5py/h5i.pxd
+++ b/h5py/h5i.pxd
@@ -20,7 +20,7 @@ from h5 cimport hid_t, hbool_t, herr_t, htri_t, hsize_t, hssize_t, hvl_t
cdef extern from "hdf5.h":
# reflection
- cdef enum H5I_type_t:
+ ctypedef enum H5I_type_t:
H5I_BADID = -1, # /*invalid Group */
H5I_FILE = 1, # /*group ID for File objects */
H5I_GROUP, # /*group ID for Group objects */
@@ -35,9 +35,14 @@ cdef extern from "hdf5.h":
H5I_NGROUPS # /*number of valid groups, MUST BE LAST! */
# --- Reflection ------------------------------------------------------------
- H5I_type_t H5Iget_type(hid_t obj_id)
- ssize_t H5Iget_name( hid_t obj_id, char *name, size_t size)
- hid_t H5Iget_file_id(hid_t obj_id)
- int H5Idec_ref(hid_t obj_id)
- int H5Iget_ref(hid_t obj_id)
- int H5Iinc_ref(hid_t obj_id)
+ H5I_type_t H5Iget_type(hid_t obj_id) except *
+ ssize_t H5Iget_name( hid_t obj_id, char *name, size_t size) except *
+ hid_t H5Iget_file_id(hid_t obj_id) except *
+ int H5Idec_ref(hid_t obj_id) except *
+ int H5Iget_ref(hid_t obj_id) except *
+ int H5Iinc_ref(hid_t obj_id) except *
+
+
+
+
+
diff --git a/h5py/h5i.pyx b/h5py/h5i.pyx
index cb0f443..805e9ac 100644
--- a/h5py/h5i.pyx
+++ b/h5py/h5i.pyx
@@ -15,13 +15,13 @@
"""
# Pyrex compile-time imports
-from defs_c cimport size_t, malloc, free
+from defs_c cimport size_t
from h5 cimport hid_t
+from utils cimport emalloc, efree
# Runtime imports
import h5
from h5 import DDict
-from errors import IdentifierError
# === Public constants and data structures ====================================
@@ -49,32 +49,28 @@ def get_type(hid_t obj_id):
Determine the type of an arbitrary HDF5 object. The return value is
always one of TYPE_*; if the ID is invalid, TYPE_BADID is returned.
"""
- cdef int retval
- retval = <int>H5Iget_type(obj_id)
- return retval
+ return <int>H5Iget_type(obj_id)
def get_name(hid_t obj_id):
""" (INT obj_id) => STRING name or None
Determine (a) name of an HDF5 object. Because an object has as many
- names as there are hard links to it, this may not be unique. If the
- object does not have a name (transient datatypes, etc.), or if the
- identifier is invalid, returns None.
+ names as there are hard links to it, this may not be unique.
"""
cdef int namelen
cdef char* name
namelen = <int>H5Iget_name(obj_id, NULL, 0)
-
if namelen <= 0:
- return None
-
- name = <char*>malloc(namelen+1)
- namelen = H5Iget_name(obj_id, name, namelen+1)
- retstring = name
- free(name)
+ raise RuntimeError("Failed to raise exception at get_name")
- return retstring
+ name = <char*>emalloc(sizeof(char)*(namelen+1))
+ try:
+ H5Iget_name(obj_id, name, namelen+1)
+ pystring = name
+ return pystring
+ finally:
+ efree(name)
def get_file_id(hid_t obj_id):
""" (INT obj_id) => INT file_id
@@ -82,42 +78,28 @@ def get_file_id(hid_t obj_id):
Obtain an identifier for the file in which this object resides,
re-opening the file if necessary.
"""
- cdef hid_t fid
- fid = H5Iget_file_id(obj_id)
- if fid < 0:
- raise IdentifierError("Failed to determine file id for object %d" % obj_id)
- return fid
+ return H5Iget_file_id(obj_id)
def inc_ref(hid_t obj_id):
""" (INT obj_id)
Increment the reference count for the given object.
"""
- cdef int retval
- retval = H5Iinc_ref(obj_id)
- if retval < 0:
- raise IdentifierError("Failed to increment reference count of object %d" % obj_id)
+ H5Iinc_ref(obj_id)
def get_ref(hid_t obj_id):
""" (INT obj_id)
Retrieve the reference count for the given object.
"""
- cdef int retval
- retval = H5Iget_ref(obj_id)
- if retval < 0:
- raise IdentifierError("Failed to determine reference count of object %d" % obj_id)
- return retval
+ return H5Iget_ref(obj_id)
def dec_ref(hid_t obj_id):
""" (INT obj_id)
Decrement the reference count for the given object.
"""
- cdef int retval
- retval = H5Idec_ref(obj_id)
- if retval < 0:
- raise IdentifierError("Failed to decrement reference count of object %d" % obj_id)
+ H5Idec_ref(obj_id)
diff --git a/h5py/h5p.pxd b/h5py/h5p.pxd
index 247c3c7..0208a71 100644
--- a/h5py/h5p.pxd
+++ b/h5py/h5p.pxd
@@ -33,75 +33,75 @@ cdef extern from "hdf5.h":
# --- Property list operations ----------------------------------------------
# General operations
- hid_t H5Pcreate(hid_t plist_id)
- hid_t H5Pcopy(hid_t plist_id)
- int H5Pget_class(hid_t plist_id)
- herr_t H5Pclose(hid_t plist_id)
- htri_t H5Pequal( hid_t id1, hid_t id2 )
+ hid_t H5Pcreate(hid_t plist_id) except *
+ hid_t H5Pcopy(hid_t plist_id) except *
+ int H5Pget_class(hid_t plist_id) except *
+ herr_t H5Pclose(hid_t plist_id) except *
+ htri_t H5Pequal( hid_t id1, hid_t id2 ) except *
# File creation properties
herr_t H5Pget_version(hid_t plist, unsigned int *super_, unsigned int* freelist,
- unsigned int *stab, unsigned int *shhdr)
- herr_t H5Pset_userblock(hid_t plist, hsize_t size)
- herr_t H5Pget_userblock(hid_t plist, hsize_t * size)
- herr_t H5Pset_sizes(hid_t plist, size_t sizeof_addr, size_t sizeof_size)
- herr_t H5Pget_sizes(hid_t plist, size_t *sizeof_addr, size_t *sizeof_size)
- herr_t H5Pset_sym_k(hid_t plist, unsigned int ik, unsigned int lk)
- herr_t H5Pget_sym_k(hid_t plist, unsigned int *ik, unsigned int *lk)
- herr_t H5Pset_istore_k(hid_t plist, unsigned int ik)
- herr_t H5Pget_istore_k(hid_t plist, unsigned int *ik )
+ unsigned int *stab, unsigned int *shhdr) except *
+ herr_t H5Pset_userblock(hid_t plist, hsize_t size) except *
+ herr_t H5Pget_userblock(hid_t plist, hsize_t * size) except *
+ herr_t H5Pset_sizes(hid_t plist, size_t sizeof_addr, size_t sizeof_size) except *
+ herr_t H5Pget_sizes(hid_t plist, size_t *sizeof_addr, size_t *sizeof_size) except *
+ herr_t H5Pset_sym_k(hid_t plist, unsigned int ik, unsigned int lk) except *
+ herr_t H5Pget_sym_k(hid_t plist, unsigned int *ik, unsigned int *lk) except *
+ herr_t H5Pset_istore_k(hid_t plist, unsigned int ik) except *
+ herr_t H5Pget_istore_k(hid_t plist, unsigned int *ik) except *
# File access
- herr_t H5Pset_fclose_degree(hid_t fapl_id, H5F_close_degree_t fc_degree)
- herr_t H5Pget_fclose_degree(hid_t fapl_id, H5F_close_degree_t *fc_degree)
- herr_t H5Pset_fapl_core( hid_t fapl_id, size_t increment, hbool_t backing_store)
- herr_t H5Pget_fapl_core( hid_t fapl_id, size_t *increment, hbool_t *backing_store)
- herr_t H5Pset_fapl_family ( hid_t fapl_id, hsize_t memb_size, hid_t memb_fapl_id )
- herr_t H5Pget_fapl_family ( hid_t fapl_id, hsize_t *memb_size, hid_t *memb_fapl_id )
- herr_t H5Pset_family_offset ( hid_t fapl_id, hsize_t offset)
- herr_t H5Pget_family_offset ( hid_t fapl_id, hsize_t *offset)
- herr_t H5Pset_fapl_log(hid_t fapl_id, char *logfile, unsigned int flags, size_t buf_size)
+ herr_t H5Pset_fclose_degree(hid_t fapl_id, H5F_close_degree_t fc_degree) except *
+ herr_t H5Pget_fclose_degree(hid_t fapl_id, H5F_close_degree_t *fc_degree) except *
+ herr_t H5Pset_fapl_core( hid_t fapl_id, size_t increment, hbool_t backing_store) except *
+ herr_t H5Pget_fapl_core( hid_t fapl_id, size_t *increment, hbool_t *backing_store) except *
+ herr_t H5Pset_fapl_family ( hid_t fapl_id, hsize_t memb_size, hid_t memb_fapl_id ) except *
+ herr_t H5Pget_fapl_family ( hid_t fapl_id, hsize_t *memb_size, hid_t *memb_fapl_id ) except *
+ herr_t H5Pset_family_offset ( hid_t fapl_id, hsize_t offset) except *
+ herr_t H5Pget_family_offset ( hid_t fapl_id, hsize_t *offset) except *
+ herr_t H5Pset_fapl_log(hid_t fapl_id, char *logfile, unsigned int flags, size_t buf_size) except *
# Dataset creation properties
- herr_t H5Pset_layout(hid_t plist, H5D_layout_t layout )
- H5D_layout_t H5Pget_layout(hid_t plist)
- herr_t H5Pset_chunk(hid_t plist, int ndims, hsize_t * dim)
- int H5Pget_chunk(hid_t plist, int max_ndims, hsize_t * dims )
- herr_t H5Pset_deflate( hid_t plist, int level)
- herr_t H5Pset_fill_value(hid_t plist_id, hid_t type_id, void *value )
- herr_t H5Pget_fill_value(hid_t plist_id, hid_t type_id, void *value )
- herr_t H5Pfill_value_defined(hid_t plist_id, H5D_fill_value_t *status )
- herr_t H5Pset_fill_time(hid_t plist_id, H5D_fill_time_t fill_time )
- herr_t H5Pget_fill_time(hid_t plist_id, H5D_fill_time_t *fill_time )
- herr_t H5Pset_alloc_time(hid_t plist_id, H5D_alloc_time_t alloc_time )
- herr_t H5Pget_alloc_time(hid_t plist_id, H5D_alloc_time_t *alloc_time )
+ herr_t H5Pset_layout(hid_t plist, H5D_layout_t layout) except *
+ H5D_layout_t H5Pget_layout(hid_t plist) except *
+ herr_t H5Pset_chunk(hid_t plist, int ndims, hsize_t * dim) except *
+ int H5Pget_chunk(hid_t plist, int max_ndims, hsize_t * dims ) except *
+ herr_t H5Pset_deflate( hid_t plist, int level) except *
+ herr_t H5Pset_fill_value(hid_t plist_id, hid_t type_id, void *value ) except *
+ herr_t H5Pget_fill_value(hid_t plist_id, hid_t type_id, void *value ) except *
+ herr_t H5Pfill_value_defined(hid_t plist_id, H5D_fill_value_t *status ) except *
+ herr_t H5Pset_fill_time(hid_t plist_id, H5D_fill_time_t fill_time ) except *
+ herr_t H5Pget_fill_time(hid_t plist_id, H5D_fill_time_t *fill_time ) except *
+ herr_t H5Pset_alloc_time(hid_t plist_id, H5D_alloc_time_t alloc_time ) except *
+ herr_t H5Pget_alloc_time(hid_t plist_id, H5D_alloc_time_t *alloc_time ) except *
herr_t H5Pset_filter(hid_t plist, H5Z_filter_t filter, unsigned int flags,
- size_t cd_nelmts, unsigned int cd_values[] )
- htri_t H5Pall_filters_avail(hid_t dcpl_id)
- int H5Pget_nfilters(hid_t plist)
+ size_t cd_nelmts, unsigned int cd_values[] ) except *
+ htri_t H5Pall_filters_avail(hid_t dcpl_id) except *
+ int H5Pget_nfilters(hid_t plist) except *
H5Z_filter_t H5Pget_filter(hid_t plist, unsigned int filter_number,
unsigned int *flags, size_t *cd_nelmts,
- unsigned int *cd_values, size_t namelen, char name[] )
+ unsigned int *cd_values, size_t namelen, char name[] ) except *
herr_t H5Pget_filter_by_id( hid_t plist_id, H5Z_filter_t filter,
unsigned int *flags, size_t *cd_nelmts,
- unsigned int cd_values[], size_t namelen, char name[] )
+ unsigned int cd_values[], size_t namelen, char name[] ) except *
herr_t H5Pmodify_filter(hid_t plist, H5Z_filter_t filter, unsigned int flags,
- size_t cd_nelmts, unsigned int cd_values[] )
- herr_t H5Premove_filter(hid_t plist, H5Z_filter_t filter )
- herr_t H5Pset_fletcher32(hid_t plist)
- herr_t H5Pset_shuffle(hid_t plist_id)
- herr_t H5Pset_szip(hid_t plist, unsigned int options_mask, unsigned int pixels_per_block)
+ size_t cd_nelmts, unsigned int cd_values[] ) except *
+ herr_t H5Premove_filter(hid_t plist, H5Z_filter_t filter ) except *
+ herr_t H5Pset_fletcher32(hid_t plist) except *
+ herr_t H5Pset_shuffle(hid_t plist_id) except *
+ herr_t H5Pset_szip(hid_t plist, unsigned int options_mask, unsigned int pixels_per_block) except *
# Transfer properties
- herr_t H5Pset_edc_check(hid_t plist, H5Z_EDC_t check)
- H5Z_EDC_t H5Pget_edc_check(hid_t plist)
+ herr_t H5Pset_edc_check(hid_t plist, H5Z_EDC_t check) except *
+ H5Z_EDC_t H5Pget_edc_check(hid_t plist) except *
# Other properties
herr_t H5Pset_cache(hid_t plist_id, int mdc_nelmts, int rdcc_nelmts,
- size_t rdcc_nbytes, double rdcc_w0)
- herr_t H5Pset_sieve_buf_size(hid_t fapl_id, hsize_t size)
+ size_t rdcc_nbytes, double rdcc_w0) except *
+ herr_t H5Pset_sieve_buf_size(hid_t fapl_id, hsize_t size) except *
herr_t H5Pset_fapl_log(hid_t fapl_id, char *logfile,
- unsigned int flags, size_t buf_size)
+ unsigned int flags, size_t buf_size) except *
diff --git a/h5py/h5p.pyx b/h5py/h5p.pyx
index bc2b6ab..2fa87eb 100644
--- a/h5py/h5p.pyx
+++ b/h5py/h5p.pyx
@@ -16,17 +16,19 @@
"""
# Pyrex compile-time imports
-from defs_c cimport malloc, free, size_t
+from defs_c cimport size_t
from h5 cimport herr_t, hid_t, htri_t, herr_t, hsize_t
from h5d cimport H5D_layout_t
from h5z cimport H5Z_filter_t
-from utils cimport tuple_to_dims, dims_to_tuple
+
+from utils cimport require_tuple, convert_dims, convert_tuple, \
+ emalloc, efree
# Runtime imports
import h5
import h5t
from h5 import DDict
-from errors import PropertyError, ConversionError
+from h5e import ConversionError
# === Public constants and data structures ====================================
@@ -47,55 +49,36 @@ def create(hid_t cls_id):
Create a new property list as an instance of a class, which should be
one of CLASS_*.
"""
- cdef hid_t retval
- retval = H5Pcreate(cls_id)
- if retval < 0:
- raise PropertyError("Failed to create instance of property list class %d" % cls_id)
- return retval
+ return H5Pcreate(cls_id)
def copy(hid_t plist):
""" (INT plist) => INT new_property_list_id
Create a new copy of an existing property list object.
"""
- cdef hid_t retval
- retval = H5Pcopy(plist)
- if retval < 0:
- raise PropertyError("Failed to copy property list %d" % plist)
- return retval
+ return H5Pcopy(plist)
def close(hid_t plist):
""" (INT plist)
"""
- cdef herr_t retval
- retval = H5Pclose(plist)
- if retval < 0:
- raise PropertyError("Failed to close property list %d" % plist)
- return retval
+ H5Pclose(plist)
def get_class(hid_t plist):
""" (INT plist) => INT class_code
Determine the class of a property list object (one of CLASS_*).
"""
- cdef int retval
- retval = H5Pget_class(plist)
- if retval < 0:
- raise PropertyError("Failed to determine class of property list %d" % plist)
- return retval
+ return H5Pget_class(plist)
def equal(hid_t plist1, hid_t plist2):
""" (INT plist1, INT plist2) => BOOL lists_are_equal
Compare two existing property lists for equality.
"""
- cdef htri_t retval
- retval = H5Pequal(plist1, plist2)
- if retval < 0:
- raise PropertyError("Could not compare for equality: %d vs %d" % (plist1, plist2))
- return bool(retval)
+ return bool(H5Pequal(plist1, plist2))
# === File creation ===========================================================
+
def get_version(hid_t plist):
""" (INT plist) => TUPLE version_info [File creation]
@@ -112,9 +95,8 @@ def get_version(hid_t plist):
cdef unsigned int stab
cdef unsigned int shhdr
- retval = H5Pget_version(plist, &super_, &freelist, &stab, &shhdr)
- if retval < 0:
- raise PropertyError("Failed to determine version info for list %d" % plist)
+ H5Pget_version(plist, &super_, &freelist, &stab, &shhdr)
+
return (super_, freelist, stab, shhdr)
def set_userblock(hid_t plist, long size):
@@ -123,22 +105,15 @@ def set_userblock(hid_t plist, long size):
Set the file user block size, in bytes. Must be a power of 2, and at
least 512.
"""
- cdef herr_t retval
- retval = H5Pset_userblock(plist, <hsize_t>size)
- if retval < 0:
- raise PropertyError("Failed to set userblock size to %d on list %d" % (size, plist))
+ H5Pset_userblock(plist, <hsize_t>size)
def get_userblock(hid_t plist):
""" (INT plist) => LONG size [File creation]
Determine the user block size, in bytes.
"""
- cdef herr_t retval
cdef hsize_t size
-
- retval = H5Pget_userblock(plist, &size)
- if retval < 0:
- raise PropertyError("Failed to determine user block size on list %d" % plist)
+ H5Pget_userblock(plist, &size)
return size
def set_sizes(hid_t plist, size_t addr, size_t size):
@@ -147,10 +122,7 @@ def set_sizes(hid_t plist, size_t addr, size_t size):
Set the addressing offsets and lengths for objects in an HDF5 file, in
bytes.
"""
- cdef herr_t retval
- retval = H5Pset_sizes(plist, addr, size)
- if retval < 0:
- raise PropertyError("Failed to set sizes on list %d (addr %d, length %d)" % (plist, addr, size))
+ H5Pset_sizes(plist, addr, size)
def get_sizes(hid_t plist):
""" (INT plist) => TUPLE sizes [File creation]
@@ -161,12 +133,9 @@ def get_sizes(hid_t plist):
0: UINT Address offsets
1: UINT Lengths
"""
- cdef herr_t retval
cdef size_t addr
cdef size_t size
- retval = H5Pget_sizes(plist, &addr, &size)
- if retval < 0:
- raise PropertyError("Failed to get sizes for plist %d" % plist)
+ H5Pget_sizes(plist, &addr, &size)
return (addr, size)
def set_sym_k(hid_t plist, unsigned int ik, unsigned int lk):
@@ -174,10 +143,7 @@ def set_sym_k(hid_t plist, unsigned int ik, unsigned int lk):
Symbol table node settings. See the HDF5 docs for H5Pset_sym_k.
"""
- cdef herr_t retval
- retval = H5Pset_sym_k(plist, ik, lk)
- if retval < 0:
- raise PropertyError("Failed to set symbol table params on list %d" % plist)
+ H5Pset_sym_k(plist, ik, lk)
def get_sym_k(hid_t plist):
""" (INT plist) => TUPLE settings [File creation]
@@ -185,13 +151,9 @@ def get_sym_k(hid_t plist):
Determine symbol table node settings. See the HDF5 docs for
H5Pget_sym_k. Return is a 2-tuple (ik, lk).
"""
- cdef herr_t retval
cdef unsigned int ik
cdef unsigned int lk
-
- retval = H5Pget_sym_k(plist, &ik, &lk)
- if retval < 0:
- raise PropertyError("Failed to get symbol table params on list %d" % plist)
+ H5Pget_sym_k(plist, &ik, &lk)
return (ik, lk)
def set_istore_k(hid_t plist, unsigned int ik):
@@ -199,22 +161,15 @@ def set_istore_k(hid_t plist, unsigned int ik):
See hdf5 docs for H5Pset_istore_k.
"""
- cdef herr_t retval
- retval = H5Pset_istore_k(plist, ik)
- if retval < 0:
- raise PropertyError("Failed to set istore params on list %d (value %d)" % (plist,ik))
+ H5Pset_istore_k(plist, ik)
def get_istore_k(hid_t plist):
""" (INT plist) => UINT ik [File creation]
See HDF5 docs for H5Pget_istore_k
"""
- cdef herr_t retval
cdef unsigned int ik
-
- retval = H5Pget_istore_k(plist, &ik)
- if retval < 0:
- raise PropertyError("Failed to get istore params on list %d" % plist)
+ H5Pget_istore_k(plist, &ik)
return ik
# === Dataset creation properties =============================================
@@ -227,10 +182,7 @@ def set_layout(hid_t plist, int layout_code):
* h5d.LAYOUT_CONTIGUOUS
* h5d.LAYOUT_CHUNKED
"""
- cdef herr_t retval
- retval = H5Pset_layout(plist, <H5D_layout_t>layout_code)
- if retval < 0:
- raise PropertyError("Failed to set layout of list %d to %d" % (plist, layout_code))
+ H5Pset_layout(plist, <H5D_layout_t>layout_code)
def get_layout(hid_t plist):
""" (INT plist) => INT layout_code [Dataset creation]
@@ -240,10 +192,7 @@ def get_layout(hid_t plist):
* h5d.LAYOUT_CONTIGUOUS
* h5d.LAYOUT_CHUNKED
"""
- cdef int retval
- retval = <int>H5Pget_layout(plist)
- if retval < 0:
- raise PropertyError("Failed to get layout of list %d" % plist)
+ return <int>H5Pget_layout(plist)
def set_chunk(hid_t plist, object chunksize):
""" (INT plist_id, TUPLE chunksize) [Dataset creation]
@@ -256,17 +205,15 @@ def set_chunk(hid_t plist, object chunksize):
cdef hsize_t* dims
dims = NULL
+ require_tuple(chunksize, 0, -1, "chunksize")
rank = len(chunksize)
- dims = tuple_to_dims(chunksize)
- if dims == NULL:
- raise ValueError("Bad input dimensions tuple: %s" % repr(chunksize))
-
- retval = H5Pset_chunk(plist, rank, dims)
- if retval < 0:
- free(dims)
- raise PropertyError("Failed to set chunk size to %s on list %d" % (str(chunksize), plist))
-
- free(dims)
+
+ dims = <hsize_t*>emalloc(sizeof(hsize_t)*rank)
+ try:
+ convert_tuple(chunksize, dims, rank)
+ H5Pset_chunk(plist, rank, dims)
+ finally:
+ efree(dims)
def get_chunk(hid_t plist):
""" (INT plist_id) => TUPLE chunk_dimensions [Dataset creation]
@@ -277,22 +224,14 @@ def get_chunk(hid_t plist):
cdef hsize_t *dims
rank = H5Pget_chunk(plist, 0, NULL)
- if rank < 0:
- raise PropertyError("Failed to get chunk size on list %d" % plist)
-
- dims = <hsize_t*>malloc(sizeof(hsize_t)*rank)
- rank = H5Pget_chunk(plist, rank, dims)
- if rank < 0:
- free(dims)
- raise PropertyError("Failed to get chunk size on list %d" % plist)
-
- tpl = dims_to_tuple(dims, rank)
- if tpl is None:
- free(dims)
- raise ConversionError("Bad dims/tuple conversion (plist %d rank %d)" % (plist, rank))
+ dims = <hsize_t*>emalloc(sizeof(hsize_t)*rank)
- free(dims)
- return tpl
+ try:
+ H5Pget_chunk(plist, rank, dims)
+ tpl = convert_dims(dims, rank)
+ return tpl
+ finally:
+ efree(dims)
# === Filter functions ========================================================
@@ -301,20 +240,14 @@ def set_deflate(hid_t plist, unsigned int level=5):
Enable DEFLATE (gzip) compression, at the given level (0-9, default 5).
"""
- cdef herr_t retval
- retval = H5Pset_deflate(plist, level)
- if retval < 0:
- raise PropertyError("Error enabling DEFLATE (level %d) on list %d" % (level, plist))
+ H5Pset_deflate(plist, level)
def set_fletcher32(hid_t plist):
""" (INT plist_id) [Dataset creation]
Enable Fletcher32 error correction on an existing list.
"""
- cdef herr_t retval
- retval = H5Pset_fletcher32(plist)
- if retval < 0:
- raise PropertyError("Error enabling Fletcher32 checksum filter on list %d" % plist)
+ H5Pset_fletcher32(plist)
def set_shuffle(hid_t plist):
""" (INT plist_id) [Dataset creation]
@@ -322,10 +255,7 @@ def set_shuffle(hid_t plist):
Enable to use of the shuffle filter. Use this immediately before the
DEFLATE filter to increase the compression ratio.
"""
- cdef herr_t retval
- retval = H5Pset_shuffle(plist)
- if retval < 0:
- raise PropertyError("Error enabling shuffle filter on list %d" % plist)
+ H5Pset_shuffle(plist)
def set_szip(hid_t plist, unsigned int options, unsigned int pixels_per_block):
""" (INT plist, UINT options, UINT pixels_per_block) [Dataset creation]
@@ -333,10 +263,7 @@ def set_szip(hid_t plist, unsigned int options, unsigned int pixels_per_block):
Enable SZIP compression. See the HDF5 docs for argument meanings, and
general restrictions on use of the SZIP format.
"""
- cdef herr_t retval
- retval = H5Pset_szip(plist, options, pixels_per_block)
- if retval < 0:
- raise PropertyError("Error enabling szip filter on list %d" % plist)
+ H5Pset_szip(plist, options, pixels_per_block)
def remove_filter(hid_t plist, int filter_class):
""" (INT plist, INT filter_class) [Dataset creation]
@@ -344,10 +271,7 @@ def remove_filter(hid_t plist, int filter_class):
Remove a filter from the pipeline. The class code is one of
h5z.FILTER_*.
"""
- cdef herr_t retval
- retval = H5Premove_filter(plist, <H5Z_filter_t>filter_class)
- if retval < 0:
- raise PropertyError("Error removing filter %d from list %d" % (filter_class, plist))
+ H5Premove_filter(plist, <H5Z_filter_t>filter_class)
# === File access =============================================================
@@ -363,10 +287,7 @@ def set_fclose_degree(hid_t fapl_id, int close_degree):
* h5f.CLOSE_STRONG
* h5f.CLOSE_DEFAULT
"""
- cdef herr_t retval
- retval = H5Pset_fclose_degree(fapl_id, <H5F_close_degree_t>close_degree)
- if retval < 0:
- raise PropertyError("Failed to set file close degree on list %d to %d" % (fapl_id, close_degree))
+ H5Pset_fclose_degree(fapl_id, <H5F_close_degree_t>close_degree)
# === Python extensions =======================================================
@@ -381,8 +302,9 @@ def py_has_filter(hid_t plist, int filter_class):
cdef unsigned int flags
cdef size_t dmp
dmp = 0
- retval = H5Pget_filter_by_id(plist, filter_class, &flags, &dmp, NULL, 0, NULL)
- if retval <= 0:
+ try:
+ H5Pget_filter_by_id(plist, filter_class, &flags, &dmp, NULL, 0, NULL)
+ except:
return False
return True
diff --git a/h5py/h5r.pxd b/h5py/h5r.pxd
index 48b29d5..edc1d8d 100644
--- a/h5py/h5r.pxd
+++ b/h5py/h5r.pxd
@@ -30,9 +30,9 @@ cdef extern from "hdf5.h":
ctypedef unsigned char hdset_reg_ref_t[12]
herr_t H5Rcreate(void *ref, hid_t loc_id, char *name, H5R_type_t ref_type,
- hid_t space_id)
- hid_t H5Rdereference(hid_t obj_id, H5R_type_t ref_type, void *ref)
- hid_t H5Rget_region(hid_t dataset, H5R_type_t ref_type, void *ref)
- H5G_obj_t H5Rget_obj_type(hid_t id, H5R_type_t ref_type, void *ref)
+ hid_t space_id) except *
+ hid_t H5Rdereference(hid_t obj_id, H5R_type_t ref_type, void *ref) except *
+ hid_t H5Rget_region(hid_t dataset, H5R_type_t ref_type, void *ref) except *
+ H5G_obj_t H5Rget_obj_type(hid_t id, H5R_type_t ref_type, void *ref) except *
diff --git a/h5py/h5r.pyx b/h5py/h5r.pyx
index b44f6c3..a4381a2 100644
--- a/h5py/h5r.pyx
+++ b/h5py/h5r.pyx
@@ -16,7 +16,6 @@ from h5g cimport H5G_obj_t
# Runtime imports
import h5
from h5 import DDict
-from errors import H5ReferenceError
# === Public constants and data structures ====================================
@@ -58,17 +57,12 @@ def create(hid_t loc_id, char* name, int ref_type, hid_t space_id=-1):
Create a new reference, either to an object or a dataset region.
"""
- cdef herr_t retval
cdef Reference ref
-
ref = Reference()
- retval = H5Rcreate(&ref.ref, loc_id, name, <H5R_type_t>ref_type, space_id)
-
- if retval < 0:
- raise H5ReferenceError("Failed to create reference on %d (\"%s\") type %d." % (loc_id, name, ref_type))
-
+ H5Rcreate(&ref.ref, loc_id, name, <H5R_type_t>ref_type, space_id)
ref.typecode = ref_type
+
return ref
def dereference(hid_t obj_id, Reference ref):
@@ -78,12 +72,7 @@ def dereference(hid_t obj_id, Reference ref):
parameter "obj_id" may be the file ID or the ID of any object which
lives in the file.
"""
- cdef hid_t retval
- retval = H5Rdereference(obj_id, <H5R_type_t>ref.typecode, &ref.ref)
- if retval < 0:
- raise H5ReferenceError("Failed to dereference.")
-
- return retval
+ return H5Rdereference(obj_id, <H5R_type_t>ref.typecode, &ref.ref)
def get_region(hid_t container_id, Reference ref):
""" (INT container_id, Reference ref) => INT dataspace_id
@@ -95,11 +84,7 @@ def get_region(hid_t container_id, Reference ref):
The given reference object must be of type TYPE_REGION.
"""
- cdef hid_t space_id
- space_id = H5Rget_region(container_id, <H5R_type_t>ref.typecode, &ref.ref)
- if space_id < 0:
- raise H5ReferenceError("Failed to retrieve region.")
- return space_id
+ return H5Rget_region(container_id, <H5R_type_t>ref.typecode, &ref.ref)
def get_obj_type(hid_t container_id, Reference ref):
""" (INT container_id, Reference ref) => INT obj_code
@@ -113,11 +98,7 @@ def get_obj_type(hid_t container_id, Reference ref):
h5g.OBJ_DATASET Dataset
h5g.OBJ_TYPE Named datatype
"""
- cdef int retval
- retval = <int>H5Rget_obj_type(container_id, <H5R_type_t>ref.typecode, &ref.ref)
- if retval < 0:
- raise H5ReferenceError("Failed to determine object type.")
- return retval
+ return <int>H5Rget_obj_type(container_id, <H5R_type_t>ref.typecode, &ref.ref)
diff --git a/h5py/h5s.pxd b/h5py/h5s.pxd
index ab7f4bc..0cb7c13 100644
--- a/h5py/h5s.pxd
+++ b/h5py/h5s.pxd
@@ -26,7 +26,7 @@ cdef extern from "hdf5.h":
int H5S_ALL, H5S_UNLIMITED, H5S_MAX_RANK
# Codes for defining selections
- cdef enum H5S_seloper_t:
+ ctypedef enum H5S_seloper_t:
H5S_SELECT_NOOP = -1,
H5S_SELECT_SET = 0,
H5S_SELECT_OR,
@@ -38,14 +38,14 @@ cdef extern from "hdf5.h":
H5S_SELECT_PREPEND,
H5S_SELECT_INVALID # Must be the last one
- cdef enum H5S_class_t:
+ ctypedef enum H5S_class_t:
H5S_NO_CLASS = -1, #/*error */
H5S_SCALAR = 0, #/*scalar variable */
H5S_SIMPLE = 1, #/*simple data space */
# no longer defined in 1.8
#H5S_COMPLEX = 2 #/*complex data space */
- cdef enum H5S_sel_type:
+ ctypedef enum H5S_sel_type:
H5S_SEL_ERROR = -1, #/* Error */
H5S_SEL_NONE = 0, #/* Nothing selected */
H5S_SEL_POINTS = 1, #/* Sequence of points selected */
@@ -55,47 +55,47 @@ cdef extern from "hdf5.h":
# --- Basic operations ------------------------------------------------------
- hid_t H5Screate(H5S_class_t type)
- hid_t H5Scopy(hid_t space_id )
- herr_t H5Sclose(hid_t space_id)
+ hid_t H5Screate(H5S_class_t type) except *
+ hid_t H5Scopy(hid_t space_id ) except *
+ herr_t H5Sclose(hid_t space_id) except *
# --- Simple dataspace operations -------------------------------------------
- hid_t H5Screate_simple(int rank, hsize_t dims[], hsize_t maxdims[])
- htri_t H5Sis_simple(hid_t space_id)
- herr_t H5Soffset_simple(hid_t space_id, hssize_t *offset )
+ hid_t H5Screate_simple(int rank, hsize_t dims[], hsize_t maxdims[]) except *
+ htri_t H5Sis_simple(hid_t space_id) except *
+ herr_t H5Soffset_simple(hid_t space_id, hssize_t *offset ) except *
- int H5Sget_simple_extent_ndims(hid_t space_id)
- int H5Sget_simple_extent_dims(hid_t space_id, hsize_t dims[], hsize_t maxdims[])
- hssize_t H5Sget_simple_extent_npoints(hid_t space_id)
- H5S_class_t H5Sget_simple_extent_type(hid_t space_id)
+ int H5Sget_simple_extent_ndims(hid_t space_id) except *
+ int H5Sget_simple_extent_dims(hid_t space_id, hsize_t dims[], hsize_t maxdims[]) except *
+ hssize_t H5Sget_simple_extent_npoints(hid_t space_id) except *
+ H5S_class_t H5Sget_simple_extent_type(hid_t space_id) except *
# --- Extents ---------------------------------------------------------------
- herr_t H5Sextent_copy(hid_t dest_space_id, hid_t source_space_id )
+ herr_t H5Sextent_copy(hid_t dest_space_id, hid_t source_space_id ) except *
herr_t H5Sset_extent_simple(hid_t space_id, int rank,
- hsize_t *current_size, hsize_t *maximum_size )
- herr_t H5Sset_extent_none(hid_t space_id)
+ hsize_t *current_size, hsize_t *maximum_size ) except *
+ herr_t H5Sset_extent_none(hid_t space_id) except *
# --- Dataspace selection ---------------------------------------------------
- H5S_sel_type H5Sget_select_type(hid_t space_id)
- hssize_t H5Sget_select_npoints(hid_t space_id)
- herr_t H5Sget_select_bounds(hid_t space_id, hsize_t *start, hsize_t *end)
+ H5S_sel_type H5Sget_select_type(hid_t space_id) except *
+ hssize_t H5Sget_select_npoints(hid_t space_id) except *
+ herr_t H5Sget_select_bounds(hid_t space_id, hsize_t *start, hsize_t *end) except *
- herr_t H5Sselect_all(hid_t space_id)
- herr_t H5Sselect_none(hid_t space_id)
- htri_t H5Sselect_valid(hid_t space_id)
+ herr_t H5Sselect_all(hid_t space_id) except *
+ herr_t H5Sselect_none(hid_t space_id) except *
+ htri_t H5Sselect_valid(hid_t space_id) except *
- hssize_t H5Sget_select_elem_npoints(hid_t space_id )
+ hssize_t H5Sget_select_elem_npoints(hid_t space_id) except *
herr_t H5Sget_select_elem_pointlist(hid_t space_id, hsize_t startpoint,
- hsize_t numpoints, hsize_t *buf)
+ hsize_t numpoints, hsize_t *buf) except *
herr_t H5Sselect_elements(hid_t space_id, H5S_seloper_t op,
- size_t num_elements, hsize_t *coord[] )
+ size_t num_elements, hsize_t *coord[] ) except *
- hssize_t H5Sget_select_hyper_nblocks(hid_t space_id )
+ hssize_t H5Sget_select_hyper_nblocks(hid_t space_id ) except *
herr_t H5Sget_select_hyper_blocklist(hid_t space_id,
- hsize_t startblock, hsize_t numblocks, hsize_t *buf )
+ hsize_t startblock, hsize_t numblocks, hsize_t *buf ) except *
herr_t H5Sselect_hyperslab(hid_t space_id, H5S_seloper_t op,
hsize_t start[], hsize_t _stride[],
- hsize_t count[], hsize_t _block[])
+ hsize_t count[], hsize_t _block[]) except *
diff --git a/h5py/h5s.pyx b/h5py/h5s.pyx
index 4b29f42..a2ff157 100644
--- a/h5py/h5s.pyx
+++ b/h5py/h5s.pyx
@@ -18,14 +18,13 @@
"""
# Pyrex compile-time imports
-from defs_c cimport malloc, free, memcpy
from h5 cimport herr_t, htri_t, hid_t, size_t, hsize_t, hssize_t
-from utils cimport tuple_to_dims, dims_to_tuple, emalloc
+from utils cimport require_tuple, convert_dims, convert_tuple, \
+ emalloc, efree
# Runtime imports
import h5
from h5 import DDict
-from errors import DataspaceError
# === Public constants and data structures ====================================
@@ -61,11 +60,7 @@ SEL_ALL = H5S_SEL_ALL
def close(hid_t space_id):
""" (INT space_id)
"""
- cdef herr_t retval
-
- retval = H5Sclose(space_id)
- if retval < 0:
- raise DataspaceError("Failed to close dataspace %d" % space_id)
+ H5Sclose(space_id)
def create(int class_code):
""" (INT class_code) => INT new_space_id
@@ -73,22 +68,14 @@ def create(int class_code):
Create a new HDF5 dataspace object, of the given class. Legal values
are CLASS_SCALAR and CLASS_SIMPLE.
"""
- cdef hid_t retval
- retval = H5Screate(<H5S_class_t>class_code)
- if retval < 0:
- raise DataspaceError("Failed to create dataspace of class %d" %d)
- return retval
+ return H5Screate(<H5S_class_t>class_code)
def copy(hid_t space_id):
""" (INT space_id) => INT new_space_id
Create a new copy of an existing dataspace.
"""
- cdef hid_t retval
- retval = H5Scopy(space_id)
- if retval < 0:
- raise DataspaceError("Failed to copy dataspace %d" % space_id)
- return retval
+ return H5Scopy(space_id)
# === Simple dataspaces =======================================================
@@ -98,41 +85,32 @@ def create_simple(object dims_tpl, object max_dims_tpl=None):
Create a simple (slab) dataspace from a tuple of dimensions. Every
element of dims_tpl must be a positive integer. You can also specify
the maximum dataspace size, via the tuple max_dims. The special
- integer h5s.SPACE_UNLIMITED, as an element of max_dims, indicates an
+ integer SPACE_UNLIMITED, as an element of max_dims, indicates an
unlimited dimension.
"""
- cdef hid_t space_id
cdef int rank
cdef hsize_t* dims
cdef hsize_t* max_dims
dims = NULL
max_dims = NULL
+ require_tuple(dims_tpl, 0, -1, "dims_tpl")
rank = len(dims_tpl)
- if max_dims_tpl is not None and len(max_dims_tpl) != rank:
- raise ValueError("Dims/max dims tuples must be the same rank: %s vs %s" % (repr(dims_tpl),repr(max_dims_tpl)))
+ require_tuple(max_dims_tpl, 1, rank, "max_dims_tpl")
try:
- dims = tuple_to_dims(dims_tpl)
- if dims == NULL:
- raise ValueError("Bad dimensions tuple: %s" % repr(dims_tpl))
+ dims = <hsize_t*>emalloc(sizeof(hsize_t)*rank)
+ convert_tuple(dims_tpl, dims, rank)
if max_dims_tpl is not None:
- max_dims = tuple_to_dims(max_dims_tpl)
- if max_dims == NULL:
- raise ValueError("Bad max dimensions tuple: %s" % repr(max_dims_tpl))
+ max_dims = <hsize_t*>emalloc(sizeof(hsize_t)*rank)
+ convert_tuple(max_dims_tpl, max_dims, rank)
- space_id = H5Screate_simple(rank, dims, max_dims)
+ return H5Screate_simple(rank, dims, max_dims)
- if space_id < 0:
- raise DataspaceError("Failed to create dataspace with dimensions %s" % str(dims_tpl))
finally:
- if dims != NULL:
- free(dims)
- if max_dims != NULL:
- free(max_dims)
-
- return space_id
+ efree(dims)
+ efree(max_dims)
def is_simple(hid_t space_id):
""" (INT space_id) => BOOL is_simple
@@ -140,64 +118,43 @@ def is_simple(hid_t space_id):
Determine if an existing dataspace is "simple". This function is
rather silly, as all HDF5 dataspaces are (currently) simple.
"""
- cdef htri_t retval
- retval = H5Sis_simple(space_id)
- if retval < 0:
- raise DataspaceError("Failed to determine simplicity of dataspace %d" % space_id)
- return bool(retval)
+ return bool(H5Sis_simple(space_id))
def offset_simple(hid_t space_id, object offset=None):
""" (INT space_id, TUPLE offset=None)
Set the offset of a dataspace. The length of the given tuple must
- match the rank of the dataspace; ValueError will be raised otherwise.
- If None is provided (default), the offsets on all axes will be set to 0.
+ match the rank of the dataspace. If None is provided (default),
+ the offsets on all axes will be set to 0.
"""
- cdef htri_t simple
cdef int rank
cdef hssize_t *dims
- cdef herr_t retval
dims = NULL
try:
- simple = H5Sis_simple(space_id)
- if simple < 0:
- raise DataspaceError("%d is not a simple dataspace" % space_id)
+ if H5Sis_simple(space_id) == 0:
+ raise ValueError("%d is not a simple dataspace" % space_id)
+ rank = H5Sget_simple_extent_ndims(space_id)
+
if offset is None:
dims = NULL
else:
- rank = H5Sget_simple_extent_ndims(space_id)
- if rank < 0:
- raise DataspaceError("Can't determine rank of dataspace %d" % space_id)
-
- if len(offset) != rank:
- raise ValueError("Length of offset tuple must match dataspace rank %d (got %s)" % (rank, repr(offset)))
+ require_tuple(offset, 0, rank, "offset")
+ dims = <hssize_t*>emalloc(sizeof(hssize_t)*rank)
+ convert_tuple(offset, <hsize_t*>dims, rank)
- # why the hell are they using hssize_t?
- dims = <hssize_t*>malloc(sizeof(hssize_t)*rank)
- for i from 0<=i<rank:
- dims[i] = offset[i]
+ H5Soffset_simple(space_id, dims)
- retval = H5Soffset_simple(space_id, dims)
- if retval < 0:
- raise DataspaceError("Failed to set offset on dataspace %d" % space_id)
finally:
- if dims != NULL:
- free(dims)
+ efree(dims)
def get_simple_extent_ndims(hid_t space_id):
""" (INT space_id) => INT rank
Determine the rank of a "simple" (slab) dataspace.
"""
- cdef int ndims
- ndims = H5Sget_simple_extent_ndims(space_id)
- if ndims < 0:
- raise DataspaceError("Failed to retrieve dimension info for dataspace %d" % space_id)
-
- return ndims
-
+ return H5Sget_simple_extent_ndims(space_id)
def get_simple_extent_dims(hid_t space_id, int maxdims=0):
""" (INT space_id, BOOL maxdims=False) => TUPLE shape
@@ -208,51 +165,34 @@ def get_simple_extent_dims(hid_t space_id, int maxdims=0):
cdef int rank
cdef hsize_t* dims
dims = NULL
- dims_tpl = None
rank = H5Sget_simple_extent_dims(space_id, NULL, NULL)
- if rank < 0:
- raise DataspaceError("Failed to retrieve dimension info for dataspace %d" % space_id)
- dims = <hsize_t*>malloc(sizeof(hsize_t)*rank)
+ dims = <hsize_t*>emalloc(sizeof(hsize_t)*rank)
try:
if maxdims:
- rank = H5Sget_simple_extent_dims(space_id, NULL, dims)
+ H5Sget_simple_extent_dims(space_id, NULL, dims)
else:
- rank = H5Sget_simple_extent_dims(space_id, dims, NULL)
- if rank < 0:
- raise DataspaceError("Failed to retrieve dimension info for dataspace %d" % space_id)
+ H5Sget_simple_extent_dims(space_id, dims, NULL)
- dims_tpl = dims_to_tuple(dims, rank)
- if dims_tpl is None:
- raise DataspaceError("Can't unwrap dimensions on dataspace %d rank %d" % (space_id, rank))
- finally:
- if dims != NULL:
- free(dims)
+ return convert_dims(dims, rank)
- return dims_tpl
+ finally:
+ efree(dims)
def get_simple_extent_npoints(hid_t space_id):
""" (INT space_id) => LONG npoints
Determine the total number of elements in a dataspace.
"""
- cdef hssize_t retval
- retval = H5Sget_simple_extent_npoints(space_id)
- if retval < 0:
- raise DataspaceError("Failed to determine number of points in dataspace %d" % space_id)
- return retval
+ return H5Sget_simple_extent_npoints(space_id)
def get_simple_extent_type(hid_t space_id):
""" (INT space_id) => INT class_code
Class code is either CLASS_SCALAR or CLASS_SIMPLE.
"""
- cdef int retval
- retval = <int>H5Sget_simple_extent_type(space_id)
- if retval < 0:
- raise DataspaceError("Can't determine type of dataspace %d" % space_id)
- return retval
+ return <int>H5Sget_simple_extent_type(space_id)
# === Extents =================================================================
@@ -261,10 +201,7 @@ def extent_copy(hid_t dest_id, hid_t source_id):
Copy one dataspace's extent to another, changing its type if necessary.
"""
- cdef herr_t retval
- retval = H5Sextent_copy(dest_id, source_id)
- if retval < 0:
- raise DataspaceError("Can't copy extent (%d to %d)" % (source_id, dest_id))
+ H5Sextent_copy(dest_id, source_id)
def set_extent_simple(hid_t space_id, object dims_tpl, object max_dims_tpl=None):
""" (INT space_id, TUPLE dims_tpl, TUPLE max_dims_tpl=None)
@@ -272,49 +209,39 @@ def set_extent_simple(hid_t space_id, object dims_tpl, object max_dims_tpl=None)
Reset the dataspace extent, via a tuple of new dimensions. Every
element of dims_tpl must be a positive integer. You can also specify
the maximum dataspace size, via the tuple max_dims. The special
- integer h5s.SPACE_UNLIMITED, as an element of max_dims, indicates an
+ integer SPACE_UNLIMITED, as an element of max_dims, indicates an
unlimited dimension.
"""
cdef int rank
cdef hsize_t* dims
cdef hsize_t* max_dims
- cdef herr_t retval
dims = NULL
max_dims = NULL
+ require_tuple(dims_tpl, 0, -1, "dims_tpl")
rank = len(dims_tpl)
- if max_dims_tpl is not None and len(max_dims_tpl) != rank:
- raise ValueError("Dims/max dims tuples must be the same rank: %s vs %s" % (repr(dims_tpl),repr(max_dims_tpl)))
+ require_tuple(max_dims_tpl, 1, rank, "max_dims_tpl")
try:
- dims = tuple_to_dims(dims_tpl)
- if dims == NULL:
- raise ValueError("Bad dimensions tuple: %s" % repr(dims_tpl))
+ dims = <hsize_t*>emalloc(sizeof(hsize_t)*rank)
+ convert_tuple(dims_tpl, dims, rank)
if max_dims_tpl is not None:
- max_dims = tuple_to_dims(max_dims_tpl)
- if max_dims == NULL:
- raise ValueError("Bad max dimensions tuple: %s" % repr(max_dims_tpl))
+ max_dims = <hsize_t*>emalloc(sizeof(hsize_t)*rank)
+ convert_tuple(max_dims_tpl, max_dims, rank)
- retval = H5Sset_extent_simple(space_id, rank, dims, max_dims)
+ H5Sset_extent_simple(space_id, rank, dims, max_dims)
- if retval < 0:
- raise DataspaceError("Failed to reset extent to %s on space %d" % (str(dims_tpl), space_id))
finally:
- if dims != NULL:
- free(dims)
- if max_dims != NULL:
- free(max_dims)
+ efree(dims)
+ efree(max_dims)
def set_extent_none(hid_t space_id):
""" (INT space_id)
Remove the dataspace extent; class changes to h5s.CLASS_NO_CLASS.
"""
- cdef herr_t retval
- retval = H5Sset_extent_non(space_id)
- if retval < 0:
- raise DataspaceError("Failed to remove extent from dataspace %d" % space_id)
+ H5Sset_extent_non(space_id)
# === General selection operations ============================================
@@ -327,11 +254,7 @@ def get_select_type(hid_t space_id):
SEL_POINTS: Point-by-point element selection in use
SEL_HYPERSLABS: Hyperslab selection in use
"""
- cdef int sel_code
- sel_code = <int>H5Sget_select_type(space_id)
- if sel_code < 0:
- raise DataspaceError("Failed to determine selection type of dataspace %d" % space_id)
- return sel_code
+ return <int>H5Sget_select_type(space_id)
def get_select_npoints(hid_t space_id):
""" (INT space_id) => LONG npoints
@@ -339,11 +262,7 @@ def get_select_npoints(hid_t space_id):
Determine the total number of points currently selected. Works for
all selection techniques.
"""
- cdef hssize_t retval
- retval = H5Sget_select_npoints(space_id)
- if retval < 0:
- raise DataspaceError("Failed to determine number of selected points in dataspace %d" % space_id)
- return retval
+ return H5Sget_select_npoints(space_id)
def get_select_bounds(hid_t space_id):
""" (INT space_id) => (TUPLE start, TUPLE end)
@@ -352,65 +271,47 @@ def get_select_bounds(hid_t space_id):
selection.
"""
cdef int rank
- cdef herr_t retval
cdef hsize_t *start
cdef hsize_t *end
start = NULL
end = NULL
rank = H5Sget_simple_extent_ndims(space_id)
- if rank < 0:
- raise DataspaceError("Failed to enumerate dimensions of %d for bounding box." % space_id)
- start = <hsize_t*>malloc(sizeof(hsize_t)*rank)
- end = <hsize_t*>malloc(sizeof(hsize_t)*rank)
+ start = <hsize_t*>emalloc(sizeof(hsize_t)*rank)
+ end = <hsize_t*>emalloc(sizeof(hsize_t)*rank)
try:
- retval = H5Sget_select_bounds(space_id, start, end)
- if retval < 0:
- raise DataspaceError("Failed to determine bounding box for space %d" % space_id)
+ H5Sget_select_bounds(space_id, start, end)
- start_tpl = dims_to_tuple(start, rank)
- end_tpl = dims_to_tuple(end, rank)
- if start_tpl == None or end_tpl == None:
- raise RuntimeError("Failed to construct return tuples.")
+ start_tpl = convert_dims(start, rank)
+ end_tpl = convert_dims(end, rank)
+ return (start_tpl, end_tpl)
finally:
- free(start)
- free(end)
-
- return (start_tpl, end_tpl)
+ efree(start)
+ efree(end)
def select_all(hid_t space_id):
""" (INT space_id)
Select all points in the dataspace.
"""
- cdef herr_t retval
- retval = H5Sselect_all(space_id)
- if retval < 0:
- raise DataspaceError("select_all failed on dataspace %d" % space_id)
+ H5Sselect_all(space_id)
def select_none(hid_t space_id):
""" (INT space_id)
Deselect entire dataspace.
"""
- cdef herr_t retval
- retval = H5Sselect_none(space_id)
- if retval < 0:
- raise DataspaceError("select_none failed on dataspace %d" % space_id)
+ H5Sselect_none(space_id)
def select_valid(hid_t space_id):
""" (INT space_id) => BOOL select_valid
Determine if the current selection falls within the dataspace extent.
"""
- cdef htri_t retval
- retval = H5Sselect_valid(space_id)
- if retval < 0:
- raise DataspaceError("Failed to determine selection status on dataspace %d" % space_id)
- return bool(retval)
+ return bool(H5Sselect_valid(space_id))
# === Point selection functions ===============================================
@@ -419,19 +320,14 @@ def get_select_elem_npoints(hid_t space_id):
Determine the number of elements selected in point-selection mode.
"""
- cdef hssize_t retval
- retval = H5Sget_select_elem_npoints(space_id)
- if retval < 0:
- raise DataspaceError("Failed to count element-selection npoints in space %d" % space_id)
- return retval
+ return H5Sget_select_elem_npoints(space_id)
def get_select_elem_pointlist(hid_t space_id):
""" (INT space_id) => LIST elements_list
Get a list of all selected elements, in point-selection mode.
- List entries <rank>-length tuples containing point coordinates.
+ List entries are <rank>-length tuples containing point coordinates.
"""
- cdef herr_t retval
cdef int rank
cdef hssize_t npoints
cdef hsize_t *buf
@@ -439,21 +335,15 @@ def get_select_elem_pointlist(hid_t space_id):
cdef int i_entry
npoints = H5Sget_select_elem_npoints(space_id)
- if npoints < 0:
- raise DataspaceError("Failed to enumerate points for pointlist, space %d" % space_id)
- elif npoints == 0:
+ if npoints == 0:
return []
rank = H5Sget_simple_extent_ndims(space_id)
- if rank < 0:
- raise DataspaceError("Failed to determine rank of space %d" % space_id)
- buf = <hsize_t*>malloc(sizeof(hsize_t)*rank*npoints)
+ buf = <hsize_t*>emalloc(sizeof(hsize_t)*rank*npoints)
try:
- retval = H5Sget_select_elem_pointlist(space_id, 0, <hsize_t>npoints, buf)
- if retval < 0:
- raise DataspaceError("Failed to retrieve pointlist for dataspace %d" % space_id)
+ H5Sget_select_elem_pointlist(space_id, 0, <hsize_t>npoints, buf)
retlist = []
for i_point from 0<=i_point<npoints:
@@ -463,7 +353,7 @@ def get_select_elem_pointlist(hid_t space_id):
retlist.append(tuple(tmp_tpl))
finally:
- free(buf)
+ efree(buf)
return retlist
@@ -473,7 +363,6 @@ def select_elements(hid_t space_id, object coord_list, int op=H5S_SELECT_SET):
Select elements using a list of points. List entries should be
<rank>-length tuples containing point coordinates.
"""
- cdef herr_t retval # Result of API call
cdef size_t nelements # Number of point coordinates
cdef hsize_t *coords # Contiguous 2D array nelements x rank x sizeof(hsize_t)
cdef size_t element_size # Size of a point record: sizeof(hsize_t)*rank
@@ -484,31 +373,27 @@ def select_elements(hid_t space_id, object coord_list, int op=H5S_SELECT_SET):
coords = NULL
rank = H5Sget_simple_extent_ndims(space_id)
- if rank < 0:
- raise DataspaceError("Failed to determine rank of space %d" % space_id)
nelements = len(coord_list)
element_size = sizeof(hsize_t)*rank
# HDF5 docs say this has to be a contiguous 2D array
- coords = <hsize_t*>malloc(element_size*nelements)
+ coords = <hsize_t*>emalloc(element_size*nelements)
try:
for i_point from 0<=i_point<nelements:
tpl = coord_list[i_point]
- if len(tpl) != rank:
- raise ValueError("All coordinate entries must be length-%d" % rank)
+ lmsg = "List element %d" % i_point
+ require_tuple(tpl, 0, rank, lmsg)
for i_entry from 0<=i_entry<rank:
coords[(i_point*rank) + i_entry] = tpl[i_entry]
- retval = H5Sselect_elements(space_id, <H5S_seloper_t>op, nelements, <hsize_t**>coords)
- if retval < 0:
- raise DataspaceError("Failed to select point list on dataspace %d" % space_id)
+ H5Sselect_elements(space_id, <H5S_seloper_t>op, nelements, <hsize_t**>coords)
+
finally:
- if coords != NULL:
- free(coords)
+ efree(coords)
# === Hyperslab selection functions ===========================================
@@ -517,11 +402,7 @@ def get_select_hyper_nblocks(hid_t space_id):
Get the number of hyperslab blocks currently selected.
"""
- cdef hssize_t nblocks
- nblocks = H5Sget_select_hyper_nblocks(space_id)
- if nblocks < 0:
- raise DataspaceError("Failed to enumerate selected hyperslab blocks in space %d" % space_id)
- return nblocks
+ return H5Sget_select_hyper_nblocks(space_id)
def get_select_hyper_blocklist(hid_t space_id):
""" (INT space_id) => LIST hyperslab_blocks
@@ -541,19 +422,12 @@ def get_select_hyper_blocklist(hid_t space_id):
cdef int i_entry
rank = H5Sget_simple_extent_ndims(space_id)
- if rank < 0:
- raise DataspaceError("Failed to determine rank of space %d" % space_id)
-
nblocks = H5Sget_select_hyper_nblocks(space_id)
- if nblocks < 0:
- raise DataspaceError("Failed to enumerate block selection on space %d" % space_id)
- buf = <hsize_t*>malloc(sizeof(hsize_t)*2*rank*nblocks)
+ buf = <hsize_t*>emalloc(sizeof(hsize_t)*2*rank*nblocks)
try:
- retval = H5Sget_select_hyper_blocklist(space_id, 0, nblocks, buf)
- if retval < 0:
- raise DataspaceError("Failed to retrieve list of hyperslab blocks from space %d" % space_id)
+ H5Sget_select_hyper_blocklist(space_id, 0, nblocks, buf)
outlist = []
for i_block from 0<=i_block<nblocks:
@@ -567,7 +441,7 @@ def get_select_hyper_blocklist(hid_t space_id):
opposite_list.append(entry)
outlist.append( (tuple(corner_list), tuple(opposite_list)) )
finally:
- free(buf)
+ efree(buf)
return outlist
@@ -580,7 +454,6 @@ def select_hyperslab(hid_t space_id, object start, object count,
Select a block region from an existing dataspace. See the HDF5
documentation for the meaning of the "block" and "op" keywords.
"""
- cdef herr_t retval
cdef int rank
cdef hsize_t* start_array
cdef hsize_t* count_array
@@ -592,53 +465,35 @@ def select_hyperslab(hid_t space_id, object start, object count,
stride_array = NULL
block_array = NULL
- rank = get_simple_extent_ndims(space_id)
- if len(start) != rank:
- raise DataspaceError('Dimensions of input "%s" must match rank of dataspace (%d)' % (repr(start), rank))
-
- if len(count) != rank:
- raise DataspaceError("Dimensions of all arguments must be the same and of rank %d" % rank)
+ # Dataspace rank. All provided tuples must match this.
+ rank = H5Sget_simple_extent_ndims(space_id)
- if stride is not None:
- if len(stride) != rank:
- raise DataspaceError("Dimensions of all arguments must be the same and of rank %d" % rank)
-
- if block is not None:
- if len(block) != rank:
- raise DataspaceError("Dimensions of all arguments must be the same and of rank %d" % rank)
+ require_tuple(start, 0, rank, "start")
+ require_tuple(count, 0, rank, "count")
+ require_tuple(stride, 1, rank, "stride")
+ require_tuple(block, 1, rank, "block")
try:
- start_array = tuple_to_dims(start)
- if start_array == NULL:
- raise ValueError("Invalid start tuple: %s" % repr(start))
-
- count_array = tuple_to_dims(count)
- if count_array == NULL:
- raise ValueError("Invalid count tuple: %s" % repr(count))
+ start_array = <hsize_t*>emalloc(sizeof(hsize_t)*rank)
+ count_array = <hsize_t*>emalloc(sizeof(hsize_t)*rank)
+ convert_tuple(start, start_array, rank)
+ convert_tuple(count, count_array, rank)
if stride is not None:
- stride_array = tuple_to_dims(stride)
- if stride_array == NULL:
- raise ValueError("Invalid stride tuple: %s" % repr(stride))
-
+ stride_array = <hsize_t*>emalloc(sizeof(hsize_t)*rank)
+ convert_tuple(stride, stride_array, rank)
if block is not None:
- block_array = tuple_to_dims(block)
- if block_array == NULL:
- raise ValueError("Invalid block tuple: %s" % repr(block))
+ block_array = <hsize_t*>emalloc(sizeof(hsize_t)*rank)
+ convert_tuple(block, block_array, rank)
- retval = H5Sselect_hyperslab(space_id, <H5S_seloper_t>op, start_array,
+ H5Sselect_hyperslab(space_id, <H5S_seloper_t>op, start_array,
stride_array, count_array, block_array)
- if retval < 0:
- raise DataspaceError("Failed to select hyperslab on dataspace %d" % space_id)
+
finally:
- if start_array != NULL:
- free(start_array)
- if count_array != NULL:
- free(count_array)
- if stride_array != NULL:
- free(stride_array)
- if block_array != NULL:
- free(block_array)
+ efree(start_array)
+ efree(count_array)
+ efree(stride_array)
+ efree(block_array)
# === Python extensions =======================================================
diff --git a/h5py/h5t.pxd b/h5py/h5t.pxd
index 0e1eaa9..f3cdba6 100644
--- a/h5py/h5t.pxd
+++ b/h5py/h5t.pxd
@@ -145,89 +145,101 @@ cdef extern from "hdf5.h":
# --- Datatype operations ---------------------------------------------------
# General operations
- hid_t H5Tcreate(H5T_class_t type, size_t size)
- hid_t H5Topen(hid_t loc, char* name)
- herr_t H5Tcommit(hid_t loc_id, char* name, hid_t type)
- htri_t H5Tcommitted(hid_t type)
- hid_t H5Tcopy(hid_t type_id)
- htri_t H5Tequal(hid_t type_id1, hid_t type_id2 )
- herr_t H5Tlock(hid_t type_id )
- H5T_class_t H5Tget_class(hid_t type_id)
- size_t H5Tget_size(hid_t type_id )
- hid_t H5Tget_super(hid_t type)
- htri_t H5Tdetect_class(hid_t type_id, H5T_class_t dtype_class)
- herr_t H5Tclose(hid_t type_id)
-
- hid_t H5Tget_native_type(hid_t type_id, H5T_direction_t direction)
+ hid_t H5Tcreate(H5T_class_t type, size_t size) except *
+ hid_t H5Topen(hid_t loc, char* name) except *
+ herr_t H5Tcommit(hid_t loc_id, char* name, hid_t type) except *
+ htri_t H5Tcommitted(hid_t type) except *
+ hid_t H5Tcopy(hid_t type_id) except *
+ htri_t H5Tequal(hid_t type_id1, hid_t type_id2 ) except *
+ herr_t H5Tlock(hid_t type_id) except *
+ H5T_class_t H5Tget_class(hid_t type_id) except *
+ size_t H5Tget_size(hid_t type_id) except? 0
+ hid_t H5Tget_super(hid_t type) except *
+ htri_t H5Tdetect_class(hid_t type_id, H5T_class_t dtype_class) except *
+ herr_t H5Tclose(hid_t type_id) except *
+
+ hid_t H5Tget_native_type(hid_t type_id, H5T_direction_t direction) except *
# Not for public API
herr_t H5Tconvert(hid_t src_id, hid_t dst_id, size_t nelmts, void *buf, void *background, hid_t plist_id) except *
ctypedef herr_t (*H5T_overflow_t)(hid_t src_id, hid_t dst_id, void *src_buf, void *dst_buf) except -1
- herr_t H5Tset_overflow(H5T_overflow_t func)
+ herr_t H5Tset_overflow(H5T_overflow_t func) except *
# Atomic datatypes
- herr_t H5Tset_size(hid_t type_id, size_t size)
+ herr_t H5Tset_size(hid_t type_id, size_t size) except *
- H5T_order_t H5Tget_order(hid_t type_id)
- herr_t H5Tset_order(hid_t type_id, H5T_order_t order)
+ H5T_order_t H5Tget_order(hid_t type_id) except *
+ herr_t H5Tset_order(hid_t type_id, H5T_order_t order) except *
- hsize_t H5Tget_precision(hid_t type_id)
- herr_t H5Tset_precision(hid_t type_id, size_t prec)
+ hsize_t H5Tget_precision(hid_t type_id) except? 0
+ herr_t H5Tset_precision(hid_t type_id, size_t prec) except *
- int H5Tget_offset(hid_t type_id)
- herr_t H5Tset_offset(hid_t type_id, size_t offset)
+ int H5Tget_offset(hid_t type_id) except *
+ herr_t H5Tset_offset(hid_t type_id, size_t offset) except *
- herr_t H5Tget_pad(hid_t type_id, H5T_pad_t * lsb, H5T_pad_t * msb )
- herr_t H5Tset_pad(hid_t type_id, H5T_pad_t lsb, H5T_pad_t msb )
+ herr_t H5Tget_pad(hid_t type_id, H5T_pad_t * lsb, H5T_pad_t * msb ) except *
+ herr_t H5Tset_pad(hid_t type_id, H5T_pad_t lsb, H5T_pad_t msb ) except *
- H5T_sign_t H5Tget_sign(hid_t type_id)
- herr_t H5Tset_sign(hid_t type_id, H5T_sign_t sign)
+ H5T_sign_t H5Tget_sign(hid_t type_id) except *
+ herr_t H5Tset_sign(hid_t type_id, H5T_sign_t sign) except *
herr_t H5Tget_fields(hid_t type_id, size_t *spos, size_t *epos,
- size_t *esize, size_t *mpos, size_t *msize )
+ size_t *esize, size_t *mpos, size_t *msize ) except *
herr_t H5Tset_fields(hid_t type_id, size_t spos, size_t epos,
- size_t esize, size_t mpos, size_t msize )
-
- size_t H5Tget_ebias(hid_t type_id)
- herr_t H5Tset_ebias(hid_t type_id, size_t ebias)
- H5T_norm_t H5Tget_norm(hid_t type_id)
- herr_t H5Tset_norm(hid_t type_id, H5T_norm_t norm)
- H5T_pad_t H5Tget_inpad(hid_t type_id)
- herr_t H5Tset_inpad(hid_t type_id, H5T_pad_t inpad)
- H5T_cset_t H5Tget_cset(hid_t type_id)
- herr_t H5Tset_cset(hid_t type_id, H5T_cset_t cset)
- H5T_str_t H5Tget_strpad(hid_t type_id)
- herr_t H5Tset_strpad(hid_t type_id, H5T_str_t strpad)
+ size_t esize, size_t mpos, size_t msize ) except *
+
+ size_t H5Tget_ebias(hid_t type_id) except? 0
+ herr_t H5Tset_ebias(hid_t type_id, size_t ebias) except *
+ H5T_norm_t H5Tget_norm(hid_t type_id) except *
+ herr_t H5Tset_norm(hid_t type_id, H5T_norm_t norm) except *
+ H5T_pad_t H5Tget_inpad(hid_t type_id) except *
+ herr_t H5Tset_inpad(hid_t type_id, H5T_pad_t inpad) except *
+ H5T_cset_t H5Tget_cset(hid_t type_id) except *
+ herr_t H5Tset_cset(hid_t type_id, H5T_cset_t cset) except *
+ H5T_str_t H5Tget_strpad(hid_t type_id) except *
+ herr_t H5Tset_strpad(hid_t type_id, H5T_str_t strpad) except *
# VLENs
- hid_t H5Tvlen_create(hid_t base_type_id)
- htri_t H5Tis_variable_str(hid_t dtype_id)
+ hid_t H5Tvlen_create(hid_t base_type_id) except *
+ htri_t H5Tis_variable_str(hid_t dtype_id) except *
# Compound data types
- int H5Tget_nmembers(hid_t type_id)
- H5T_class_t H5Tget_member_class(hid_t type_id, int member_no)
- char* H5Tget_member_name(hid_t type_id, unsigned membno)
- hid_t H5Tget_member_type(hid_t type_id, unsigned membno)
- int H5Tget_member_offset(hid_t type_id, int membno)
- int H5Tget_member_index(hid_t type_id, char* name)
+ int H5Tget_nmembers(hid_t type_id) except *
+ H5T_class_t H5Tget_member_class(hid_t type_id, int member_no) except *
+ char* H5Tget_member_name(hid_t type_id, unsigned membno) except? NULL
+ hid_t H5Tget_member_type(hid_t type_id, unsigned membno) except *
+ int H5Tget_member_offset(hid_t type_id, int membno) except *
+ int H5Tget_member_index(hid_t type_id, char* name) except *
herr_t H5Tinsert(hid_t parent_id, char *name, size_t offset,
- hid_t member_id)
- herr_t H5Tpack(hid_t type_id)
+ hid_t member_id) except *
+ herr_t H5Tpack(hid_t type_id) except *
# Enumerated types
- hid_t H5Tenum_create(hid_t base_id)
- herr_t H5Tenum_insert(hid_t type, char *name, void *value)
- herr_t H5Tenum_nameof( hid_t type, void *value, char *name, size_t size )
- herr_t H5Tenum_valueof( hid_t type, char *name, void *value )
- herr_t H5Tget_member_value(hid_t type, unsigned int memb_no, void *value )
+ hid_t H5Tenum_create(hid_t base_id) except *
+ herr_t H5Tenum_insert(hid_t type, char *name, void *value) except *
+ herr_t H5Tenum_nameof( hid_t type, void *value, char *name, size_t size ) except *
+ herr_t H5Tenum_valueof( hid_t type, char *name, void *value ) except *
+ herr_t H5Tget_member_value(hid_t type, unsigned int memb_no, void *value ) except *
# Array data types
- hid_t H5Tarray_create(hid_t base_id, int ndims, hsize_t dims[], int perm[])
- int H5Tget_array_ndims(hid_t type_id)
- int H5Tget_array_dims(hid_t type_id, hsize_t dims[], int perm[])
+ hid_t H5Tarray_create(hid_t base_id, int ndims, hsize_t dims[], int perm[]) except *
+ int H5Tget_array_ndims(hid_t type_id) except *
+ int H5Tget_array_dims(hid_t type_id, hsize_t dims[], int perm[]) except *
# Opaque data types
- herr_t H5Tset_tag(hid_t type_id, char* tag)
- char* H5Tget_tag(hid_t type_id)
+ herr_t H5Tset_tag(hid_t type_id, char* tag) except *
+ char* H5Tget_tag(hid_t type_id) except? NULL
+
+# === Custom C API ============================================================
+
+# Close the datatype, ignoring all errors.
+cdef herr_t PY_H5Tclose(hid_t type_id) except *
+
+
+
+
+
+
+
diff --git a/h5py/h5t.pyx b/h5py/h5t.pyx
index 36c7f96..93cba17 100644
--- a/h5py/h5t.pyx
+++ b/h5py/h5t.pyx
@@ -53,22 +53,37 @@
# Pyrex compile-time imports
-from defs_c cimport malloc, free
+from defs_c cimport free
from h5 cimport herr_t, hid_t, size_t, hsize_t, htri_t
-from h5e cimport H5Eset_auto
-from python cimport PyTuple_New, PyTuple_SetItem, Py_INCREF
from h5p cimport H5P_DEFAULT
-cimport numpy
-from numpy cimport dtype
-from utils cimport create_ieee_complex64, create_ieee_complex128,\
- tuple_to_dims, dims_to_tuple
+from h5e cimport err_c, pause_errors, resume_errors
+from numpy cimport dtype, ndarray
+
+from utils cimport emalloc, efree, \
+ create_ieee_complex64, create_ieee_complex128, \
+ require_tuple, convert_dims, convert_tuple
# Runtime imports
import h5
from h5 import DDict
-from errors import DatatypeError, ConversionError
+from h5e import ConversionError
import sys
+# === Custom C API ============================================================
+
+cdef herr_t PY_H5Tclose(hid_t type_id) except *:
+ # Unconditionally close a datatype, ignoring all errors.
+
+ cdef err_c cookie
+ cdef herr_t retval
+ cookie = pause_errors()
+ try:
+ retval = H5Tclose(type_id)
+ finally:
+ resume_errors(cookie)
+
+ return retval
+
# === Public constants and data structures ====================================
# Enumeration H5T_class_t
@@ -150,7 +165,7 @@ NATIVE_INT64 = H5T_NATIVE_INT64
NATIVE_UINT64 = H5T_NATIVE_UINT64
# Null terminated (C) string type
-CSTRING = H5T_C_S1
+C_S1 = H5T_C_S1
# === General datatype operations =============================================
@@ -160,55 +175,35 @@ def create(int classtype, size_t size):
Create a new HDF5 type object. Legal values are COMPOUND,
OPAQUE, ENUM
"""
- cdef hid_t retval
- retval = H5Tcreate(<H5T_class_t>classtype, size)
- if retval < 0:
- raise DatatypeError("Failed to create datatype of class %s, size %d" % (str(classtype), size))
- return retval
+ return H5Tcreate(<H5T_class_t>classtype, size)
def open(hid_t group_id, char* name):
""" (INT group_id, STRING name) => INT type_id
Open a named datatype from a file.
"""
- cdef hid_t retval
- retval = H5Topen(group_id, name)
- if retval < 0:
- raise DatatypeError('Failed to open datatype "%s" on group %d' % (name, group_id))
- return retval
+ return H5Topen(group_id, name)
def commit(hid_t loc_id, char* name, hid_t type_id):
""" (INT group_id, STRING name, INT type_id)
Commit a transient datatype to a named datatype in a file.
"""
- cdef herr_t retval
- retval = H5Tcommit(loc_id, name, type_id)
- if retval < 0:
- raise DatatypeError("Failed to commit datatype %d under group %d with name '%s'" % (type_id, loc_id, name))
+ return H5Tcommit(loc_id, name, type_id)
def committed(hid_t type_id):
""" (INT type_id) => BOOL is_comitted
Determine if a given type object is named (T) or transient (F).
"""
- cdef htri_t retval
- retval = H5Tcommitted(type_id)
- if retval < 0:
- raise DatatypeError("Failed to determine status of datatype %d" % type_id)
- return bool(retval)
+ return H5Tcommitted(type_id)
def copy(hid_t type_id):
""" (INT type_id) => INT new_type_id
Copy an existing HDF type object.
"""
-
- cdef hid_t retval
- retval = H5Tcopy(type_id)
- if retval < 0:
- raise DatatypeError("Failed to copy datatype %d" % type_id)
- return retval
+ return H5Tcopy(type_id)
def equal(hid_t typeid_1, hid_t typeid_2):
""" (INT typeid_1, INT typeid_2) => BOOL types_are_equal
@@ -216,11 +211,7 @@ def equal(hid_t typeid_1, hid_t typeid_2):
Test whether two identifiers point to the same datatype object. Note
this does NOT perform any kind of logical comparison.
"""
- cdef htri_t retval
- retval = H5Tequal(typeid_1, typeid_2)
- if retval < 0:
- raise DatatypeError("Failed to test datatypes for equality: %d and %d" % (typeid_1, typeid_2))
- return bool(retval)
+ return bool(H5Tequal(typeid_1, typeid_2))
def lock(hid_t type_id):
""" (INT type_id)
@@ -228,45 +219,28 @@ def lock(hid_t type_id):
Lock a datatype, which makes it immutable and indestructible. Once
locked, it can't be unlocked.
"""
- cdef herr_t retval
- retval = H5Tlock(type_id)
- if retval < 0:
- raise DatatypeError("Failed to lock datatype %d" % type_id)
+ H5Tlock(type_id)
def get_class(hid_t type_id):
""" (INT type_id) => INT class
Get <type_id>'s class.
"""
-
- cdef int classtype
- classtype = <int>H5Tget_class(type_id)
- if classtype < 0:
- raise DatatypeError("Failed to determine class of datatype %d" % type_id)
- return classtype
+ return <int>H5Tget_class(type_id)
def get_size(hid_t type_id):
""" (INT type_id) => INT size
Determine the total size of a datatype, in bytes.
"""
- cdef size_t retval
- retval = H5Tget_size(type_id)
- if retval == 0:
- raise DatatypeError("Can't determine size of datatype %d (got 0)" % type_id)
- return retval
+ return H5Tget_size(type_id)
def get_super(hid_t type_id):
""" (INT type_id) => INT super_type_id
Determine the parent type of an array or enumeration datatype.
"""
-
- cdef hid_t stype
- stype = H5Tget_super(type_id)
- if stype < 0:
- raise DatatypeError("Can't determine base datatype of %d" % type_id)
- return stype
+ return H5Tget_super(type_id)
def get_native_type(hid_t type_id, int direction):
""" (INT type_id, INT direction) => INT new_type_id
@@ -279,24 +253,14 @@ def get_native_type(hid_t type_id, int direction):
These determine which direction the list of native datatypes is
searched; see the HDF5 docs for a definitive list.
"""
- cdef hid_t retval
- retval = H5Tget_native_type(type_id, <H5T_direction_t>direction)
- if retval < 0:
- raise DatatypeError("Can't determine native equivalent of %d" % type_id)
- return retval
+ return H5Tget_native_type(type_id, <H5T_direction_t>direction)
def detect_class(hid_t type_id, int classtype):
""" (INT type_id, INT class) => BOOL class_is_present
Determine if a member of class <class> exists in <type_id>
"""
-
- cdef htri_t retval
- retval = H5Tdetect_class(type_id, <H5T_class_t>classtype)
- if retval < 0:
- raise DatatypeError("Couldn't inspect datatype %d for class %s" % (type_id, str(classtype)))
- return bool(retval)
-
+ return bool(H5Tdetect_class(type_id, <H5T_class_t>classtype))
def close(hid_t type_id, int force=0):
""" (INT type_id, BOOL force=False)
@@ -305,10 +269,10 @@ def close(hid_t type_id, int force=0):
for exception handlers, when you're not sure if you've got an immutable
datatype.
"""
- cdef herr_t retval
- retval = H5Tclose(type_id)
- if retval < 0 and force:
- raise DatatypeError("Failed to close datatype %d" % type_id)
+ if force:
+ PY_H5Tclose(type_id)
+ else:
+ H5Tclose(type_id)
# === Atomic datatype operations ==============================================
# H5Tget_size, H5Tset_size, H5Tget_order, H5Tset_order, H5Tget_precision, \
@@ -320,11 +284,7 @@ def set_size(hid_t type_id, size_t size):
Set the total size of the datatype, in bytes. Useful mostly for
string types.
"""
- cdef herr_t retval
- retval = H5Tset_size(type_id, size)
- if retval < 0:
- raise DatatypeError("Failed to set size of datatype %d to %s" % (type_id, size))
- return retval
+ H5Tset_size(type_id, size)
def get_order(hid_t type_id):
""" (INT type_id) => INT order
@@ -334,11 +294,7 @@ def get_order(hid_t type_id):
ORDER_BE
ORDER_NATIVE
"""
- cdef int order
- order = <int>H5Tget_order(type_id)
- if order < 0:
- raise DatatypeError("Failed to determine order of datatype %d" % type_id)
- return order
+ return <int>H5Tget_order(type_id)
def set_order(hid_t type_id, int order):
""" (INT type_id, INT order)
@@ -348,10 +304,7 @@ def set_order(hid_t type_id, int order):
ORDER_BE
ORDER_NATIVE
"""
- cdef herr_t retval
- retval = H5Tset_order(type_id, <H5T_order_t>order)
- if retval < 0:
- raise DatatypeError("Failed to set order of datatype %d" % type_id)
+ H5Tset_order(type_id, <H5T_order_t>order)
def get_sign(hid_t type_id):
""" (INT type_id) => INT sign
@@ -360,11 +313,7 @@ def get_sign(hid_t type_id):
SGN_NONE: Unsigned
SGN_2: Signed 2's complement
"""
- cdef int retval
- retval = <int>H5Tget_sign(type_id)
- if retval < 0:
- raise DatatypeError("Failed to get sign of datatype %d" % type_id)
- return retval
+ return <int>H5Tget_sign(type_id)
def set_sign(hid_t type_id, int sign):
""" (INT type_id, INT sign)
@@ -373,11 +322,7 @@ def set_sign(hid_t type_id, int sign):
SGN_NONE: Unsigned
SGN_2: Signed 2's complement
"""
- cdef herr_t retval
- retval = H5Tset_sign(type_id, <H5T_sign_t>sign)
- if retval < 0:
- raise DatatypeError("Failed to set sign of datatype %d" % type_id)
-
+ H5Tset_sign(type_id, <H5T_sign_t>sign)
def is_variable_str(hid_t type_id):
""" (INT type_id) => BOOL is_variable
@@ -386,11 +331,7 @@ def is_variable_str(hid_t type_id):
Please note that reading/writing data in this format is impossible;
only fixed-length strings are currently supported.
"""
- cdef htri_t retval
- retval = H5Tis_variable_str(type_id)
- if retval < 0:
- raise DatatypeError("Failed to inspect type %d" % type_id)
- return bool(retval)
+ return bool(H5Tis_variable_str(type_id))
# === Compound datatype operations ============================================
# get_nmembers
@@ -407,11 +348,7 @@ def get_nmembers(hid_t type_id):
Determine the number of members in a compound or enumerated type.
"""
- cdef int retval
- retval = H5Tget_nmembers(type_id)
- if retval < 0:
- raise DatatypeError("Failed to determine members of datatype %d" % type_id)
- return retval
+ return H5Tget_nmembers(type_id)
def get_member_class(hid_t type_id, int member):
""" (INT type_id, INT member_index) => INT class
@@ -419,11 +356,8 @@ def get_member_class(hid_t type_id, int member):
Determine the datatype class of the member of a compound type,
identified by its index (must be 0 <= idx <= nmembers).
"""
+ return H5Tget_member_class(type_id, member)
- cdef int retval
- retval = H5Tget_member_class(type_id, member)
- if retval < 0:
- raise DatatypeError()
def get_member_name(hid_t type_id, int member):
""" (INT type_id, INT member_index) => STRING name
@@ -433,14 +367,17 @@ def get_member_name(hid_t type_id, int member):
"""
cdef char* name
- cdef object pyname
- name = NULL
+
name = H5Tget_member_name(type_id, member)
- if name != NULL:
+ if name == NULL:
+ raise RuntimeError("Failed to catch exception in get_member_name()")
+ try:
pyname = name
+ finally:
free(name)
- return pyname
- raise DatatypeError()
+
+ return pyname
+
def get_member_index(hid_t type_id, char* name):
""" (INT type_id, STRING name) => INT index
@@ -448,11 +385,7 @@ def get_member_index(hid_t type_id, char* name):
Determine the index of a member of a compound or enumerated datatype
identified by a string name.
"""
- cdef int retval
- retval = H5Tget_member_index(type_id, name)
- if retval < 0:
- raise DatatypeError("Failed to determine index of field '%' in datatype %d" % (name, type_id))
- return retval
+ return H5Tget_member_index(type_id, name)
def get_member_offset(hid_t type_id, int member):
""" (INT type_id, INT member_index) => INT offset
@@ -471,12 +404,7 @@ def get_member_type(hid_t type_id, int member):
Create a copy of a member of a compound datatype, identified by its
index. You are responsible for closing it when finished.
"""
- cdef hid_t retval
- retval = H5Tget_member_type(type_id, member)
- if retval < 0:
- raise DataTypeError
- return retval
-
+ return H5Tget_member_type(type_id, member)
def insert(hid_t type_id, char* name, size_t offset, hid_t field_id):
""" (INT compound_type_id, STRING name, INT offset, INT member_type)
@@ -485,10 +413,7 @@ def insert(hid_t type_id, char* name, size_t offset, hid_t field_id):
datatype. <offset> is the offset in bytes from the beginning of the
compound type.
"""
- cdef herr_t retval
- retval = H5Tinsert(type_id, name, offset, field_id)
- if retval < 0:
- raise DatatypeError("Failed to insert field %s into compound type" % name)
+ H5Tinsert(type_id, name, offset, field_id)
def pack(hid_t type_id):
""" (INT type_id)
@@ -496,12 +421,7 @@ def pack(hid_t type_id):
Recursively removes padding (introduced on account of e.g. compiler
alignment rules) from a compound datatype.
"""
-
- cdef herr_t retval
- retval = H5Tpack(type_id)
- if retval < 0:
- raise DatatypeError("Failed to pack datatype %d" % type_id)
- return retval
+ H5Tpack(type_id)
# === Array datatype operations ===============================================
# array_create
@@ -516,54 +436,44 @@ def array_create(hid_t base, object dims_tpl):
dimensions given via a tuple of non-negative integers. "Unlimited"
dimensions are not allowed.
"""
- cdef int rank
+ cdef hsize_t rank
cdef hsize_t *dims
- cdef hid_t type_id
- rank = len(dims_tpl)
+ dims = NULL
- dims = tuple_to_dims(dims_tpl)
- if dims == NULL:
- raise ValueError("Invalid dimensions tuple: %s" % str(dims_tpl))
- type_id = H5Tarray_create(base, rank, dims, NULL)
- free(dims)
+ require_tuple(dims_tpl, 0, -1, "dims_tpl")
+ rank = len(dims_tpl)
+ dims = <hsize_t*>emalloc(sizeof(hsize_t)*rank)
- if type_id < 0:
- raise DatatypeError("Failed to create datatype based on %d, dimensions %s" % (base, str(dims_tpl)))
- return type_id
+ try:
+ convert_tuple(dims_tpl, dims, rank)
+ return H5Tarray_create(base, rank, dims, NULL)
+ finally:
+ efree(dims)
def get_array_ndims(hid_t type_id):
""" (INT type_id) => INT rank
Get the rank of the given array datatype.
"""
- cdef int n
- n = H5Tget_array_ndims(type_id)
- if n < 0:
- raise DatatypeError("Failed to determine rank of array datatype %d" % type_id)
- return n
+ return H5Tget_array_ndims(type_id)
def get_array_dims(hid_t type_id):
""" (INT type_id) => TUPLE dimensions
Get the dimensions of the given array datatype as a tuple of integers.
"""
- cdef int rank
+ cdef hsize_t rank
cdef hsize_t* dims
- cdef object dims_tpl
dims = NULL
rank = H5Tget_array_dims(type_id, NULL, NULL)
- if rank < 0:
- raise DatatypeError("Failed to determine dimensions of datatype %d" % type_id)
-
- dims = <hsize_t*>malloc(sizeof(hsize_t)*rank)
- rank = H5Tget_array_dims(type_id, dims, NULL)
- dims_tpl = dims_to_tuple(dims, rank)
- free(dims)
- if dims_tpl is None:
- raise DatatypeError("Failed to determine dimensions of datatype %d: tuple conversion error" % type_id)
+ dims = <hsize_t*>emalloc(sizeof(hsize_t)*rank)
+ try:
+ H5Tget_array_dims(type_id, dims, NULL)
+ return convert_dims(dims, rank)
+ finally:
+ efree(dims)
- return dims_tpl
# === Enumeration datatypes ===================================================
# hid_t H5Tenum_create(hid_t base_id)
@@ -579,11 +489,7 @@ def enum_create(hid_t base_id):
Create a new enumerated type based on parent type <base_type_id>
"""
- cdef hid_t retval
- retval = H5Tenum_create(base_id)
- if retval < 0:
- raise DatatypeError("Failed to create enum of class %d" % base_id)
- return retval
+ return H5Tenum_create(base_id)
cdef void _enum_convert(hid_t type_id, long long *buf, int reverse) except *:
# Convert the long long value in "buf" to the native representation
@@ -627,38 +533,34 @@ def enum_insert(hid_t type_id, char* name, long long value):
try:
buf = value
_enum_convert(type_id, &buf, 0)
- retval = H5Tenum_insert(type_id, name, &buf)
- if retval < 0:
- raise DatatypeError("Failed to insert '%s' (value %d) into enum %d" % (name, value, type_id))
+ return H5Tenum_insert(type_id, name, &buf)
finally:
if ptype:
- H5Tclose(ptype)
+ PY_H5Tclose(ptype)
def enum_nameof(hid_t type_id, long long value):
""" (INT type_id, LLONG value) => STRING name
Determine the name associated with the given value. Due to a
limitation of the HDF5 library, this can only retrieve names up to
- 1023 characters; otherwise, DatatypeError is raised.
+ 1023 characters.
"""
cdef herr_t retval
cdef char* name
cdef long long buf
- name = <char*>malloc(1024)
+ name = <char*>emalloc(1024)
try:
buf = value
_enum_convert(type_id, &buf, 0)
retval = H5Tenum_nameof(type_id, &buf, name, 1024)
- if retval < 0:
- raise DatatypeError("Failed to determine enum name of %d" % value)
+ if retval < 0: # not sure whether H5Tenum_nameof will actually log an error
+ raise RuntimeError("Failed to determine enum name of %d" % value)
retstring = name
-
+ return retstring
finally:
- free(name)
-
- return retstring
+ efree(name)
def enum_valueof(hid_t type_id, char* name):
""" (INT type_id, STRING name) => LONG value)
@@ -668,11 +570,9 @@ def enum_valueof(hid_t type_id, char* name):
cdef herr_t retval
cdef long long buf
- retval = H5Tenum_valueof(type_id, name, &buf)
- if retval < 0:
- raise DatatypeError("Failed to recover value of %s" % name)
-
+ H5Tenum_valueof(type_id, name, &buf)
_enum_convert(type_id, &buf, 1)
+
return buf
def get_member_value(hid_t type_id, unsigned int idx):
@@ -682,26 +582,17 @@ def get_member_value(hid_t type_id, unsigned int idx):
"""
cdef herr_t retval
cdef hid_t ptype
- cdef long long *data_ptr
- data_ptr = <long long*>malloc(sizeof(long long))
+ cdef long long val
+ ptype = 0
try:
ptype = H5Tget_super(type_id)
- if ptype < 0:
- raise DatatypeError("Failed to get parent type of enum %d" % type_id)
-
- retval = H5Tget_member_value(type_id, idx, data_ptr)
- if retval < 0:
- raise DatatypeError("Failed to obtain value of element %d of enum %d" % (idx, type_id))
-
- retval = H5Tconvert(ptype, H5T_NATIVE_LLONG, 1, data_ptr, NULL, H5P_DEFAULT)
- if retval < 0:
- raise DatatypeError("Failed to postconvert integer for enum retrieval")
+ H5Tget_member_value(type_id, idx, &val)
+ H5Tconvert(ptype, H5T_NATIVE_LLONG, 1, &val, NULL, H5P_DEFAULT)
+ return val
finally:
- H5Tclose(ptype)
- interm = data_ptr[0]
- free(data_ptr)
- return interm
+ if ptype:
+ PY_H5Tclose(ptype)
# === Opaque datatypes ========================================================
@@ -710,11 +601,7 @@ def set_tag(hid_t type_id, char* tag):
Set the a string describing the contents of an opaque datatype
"""
- cdef herr_t retval
- retval = H5Tset_tag(type_id, tag)
- if retval < 0:
- raise DatatypeError("Failed to set opaque data tag '%s' on type %d" % (tag, type_id))
- return retval
+ H5Tset_tag(type_id, tag)
def get_tag(hid_t type_id):
""" (INT type_id) => STRING tag
@@ -722,16 +609,15 @@ def get_tag(hid_t type_id):
Get the tag associated with an opaque datatype
"""
cdef char* buf
- cdef object tag
buf = NULL
buf = H5Tget_tag(type_id)
if buf == NULL:
- raise DatatypeError("Failed to get opaque data tag for type %d" % type_id)
+ raise RuntimeError("Failed to raise exception on H5Tget_tag")
tag = buf
free(buf)
- return tag
+ return tag
# === Custom Python additions =================================================
@@ -886,7 +772,7 @@ def py_h5t_to_dtype(hid_t type_id, object byteorder=None,
field_types.append(py_h5t_to_dtype(tmp_id, byteorder,
None, complex_names))
finally:
- H5Tclose(tmp_id)
+ PY_H5Tclose(tmp_id)
# 1. Only a particular (ordered) subset is requested
@@ -925,14 +811,14 @@ def py_h5t_to_dtype(hid_t type_id, object byteorder=None,
# Superclass must be an integer, so only provide byteorder.
typeobj = py_attach_enum(edct, py_h5t_to_dtype(super_tid, byteorder))
finally:
- H5Tclose(super_tid)
+ PY_H5Tclose(super_tid)
elif classtype == H5T_ARRAY:
super_tid = get_super(type_id)
try:
base_dtype = py_h5t_to_dtype(super_tid, byteorder, compound_names, complex_names)
finally:
- H5Tclose(super_tid)
+ PY_H5Tclose(super_tid)
shape = get_array_dims(type_id)
typeobj = dtype( (base_dtype, shape) )
else:
@@ -943,7 +829,7 @@ def py_h5t_to_dtype(hid_t type_id, object byteorder=None,
return typeobj
-def py_dtype_to_h5t(numpy.dtype dtype_in, object complex_names=None):
+def py_dtype_to_h5t(dtype dtype_in, object complex_names=None):
""" ( DTYPE dtype_in, TUPLE complex_names=None) => INT type_id
Given a Numpy dtype object, generate a byte-for-byte memory-compatible
@@ -1028,7 +914,7 @@ def py_dtype_to_h5t(numpy.dtype dtype_in, object complex_names=None):
try:
type_out = array_create(basetype, dtype_in.subdtype[1])
finally:
- H5Tclose(basetype)
+ PY_H5Tclose(basetype)
else:
type_out = create(H5T_OPAQUE, length)
@@ -1081,7 +967,7 @@ def py_attach_enum(object enumdict, object basetype):
"""
return dtype( (basetype, [( (enumdict, 'enum'), basetype )] ) )
-def py_recover_enum(numpy.dtype dtype_in):
+def py_recover_enum(dtype dtype_in):
""" (DTYPE dtype_with_enum) => DICT enum
Extract the enum dictionary from a Numpy dtype object
@@ -1129,7 +1015,7 @@ def py_can_convert_dtype(object dt, object complex_names=None):
pass
if tid:
- H5Tclose(tid)
+ PY_H5Tclose(tid)
return can_convert
diff --git a/h5py/h5z.pxd b/h5py/h5z.pxd
index 6b480a6..0a9e9de 100644
--- a/h5py/h5z.pxd
+++ b/h5py/h5z.pxd
@@ -51,8 +51,8 @@ cdef extern from "hdf5.h":
H5Z_NO_EDC = 2
# --- Filter API ----------------------------------------------------------
- htri_t H5Zfilter_avail(H5Z_filter_t id_)
- herr_t H5Zget_filter_info(H5Z_filter_t filter_, unsigned int *filter_config_flags)
+ htri_t H5Zfilter_avail(H5Z_filter_t id_) except *
+ herr_t H5Zget_filter_info(H5Z_filter_t filter_, unsigned int *filter_config_flags) except *
diff --git a/h5py/h5z.pyx b/h5py/h5z.pyx
index 3860870..161e3d7 100644
--- a/h5py/h5z.pyx
+++ b/h5py/h5z.pyx
@@ -21,7 +21,6 @@ from h5 cimport herr_t, htri_t
# Runtime imports
import h5
from h5 import DDict
-from errors import FilterError
# === Public constants and data structures ====================================
@@ -58,19 +57,12 @@ NO_EDC = H5Z_NO_EDC
def filter_avail(int filter_id):
- cdef htri_t retval
- retval = H5Zfilter_avail(<H5Z_filter_t>filter_id)
- if retval < 0:
- raise FilterError("Can't determine availability of filter %d" % filter_id)
- return bool(retval)
+ return bool(H5Zfilter_avail(<H5Z_filter_t>filter_id))
def get_filter_info(int filter_id):
- cdef herr_t retval
cdef unsigned int flags
- retval = H5Zget_filter_info(<H5Z_filter_t>filter_id, &flags)
- if retval < 0:
- raise FilterError("Can't determine flags of filter %d" % filter_id)
+ H5Zget_filter_info(<H5Z_filter_t>filter_id, &flags)
return flags
# === Python extensions =======================================================
diff --git a/h5py/python.pxd b/h5py/python.pxd
index dd7e920..ef1aabe 100644
--- a/h5py/python.pxd
+++ b/h5py/python.pxd
@@ -73,7 +73,7 @@ cdef extern from "Python.h":
void* PyExc_Exception # Not allowed to declare objects "extern C" (why not?)
void PyErr_SetString(object type_, char* msg)
void PyErr_SetNone(object type_)
-
+ void PyErr_SetObject(object type_, object args)
object PyErr_NewException(char* name, object base, object dict_)
diff --git a/h5py/tests/__init__.py b/h5py/tests/__init__.py
index e741023..eea4fb6 100644
--- a/h5py/tests/__init__.py
+++ b/h5py/tests/__init__.py
@@ -13,14 +13,8 @@
import unittest
import sys
import test_h5a
-import test_h5f
-import test_h5g
-import test_h5i
-import test_h5d
-import test_h5p
-import test_h5
-
-from h5py import h5a, h5f, h5g, h5d, h5s, h5i, h5z, h5p, highlevel
+
+from h5py import h5a, h5f, h5g, h5d, h5s, h5i, h5z, h5p#, highlevel
TEST_CASES = (test_h5a.TestH5A,)# test_h5f.TestH5F, test_h5g.TestH5G,
#test_h5i.TestH5I, test_h5d.TestH5D, test_h5.TestH5,
diff --git a/h5py/tests/test_h5a.py b/h5py/tests/test_h5a.py
index b1d81eb..98114b9 100644
--- a/h5py/tests/test_h5a.py
+++ b/h5py/tests/test_h5a.py
@@ -68,8 +68,8 @@ class TestH5A(unittest.TestCase):
h5g.close(obj)
deletecopy(fid, filename)
- self.assertRaises(TypeError, h5a.create, -1, "FOOBAR", -1, -1)
- self.assertRaises(TypeError, h5a.write, -1, arr_ref)
+ self.assertRaises(ValueError, h5a.create, -1, "FOOBAR", -1, -1)
+ self.assertRaises(ValueError, h5a.write, -1, arr_ref)
def test_open_idx(self):
for idx, name in enumerate(ATTRIBUTES_ORDER):
@@ -77,7 +77,7 @@ class TestH5A(unittest.TestCase):
self.assert_(self.is_attr(aid), "Open: index %d" % idx)
h5a.close(aid)
- self.assertRaises(TypeError, h5a.open_idx, -1, 0)
+ self.assertRaises(ValueError, h5a.open_idx, -1, 0)
def test_open_name(self):
for name in ATTRIBUTES:
@@ -85,7 +85,7 @@ class TestH5A(unittest.TestCase):
self.assert_(self.is_attr(aid), 'Open: name "%s"' % name)
h5a.close(aid)
- self.assertRaises(TypeError, h5a.open_name, -1, "foo")
+ self.assertRaises(ValueError, h5a.open_name, -1, "foo")
def test_close(self):
aid = h5a.open_idx(self.obj, 0)
@@ -93,7 +93,7 @@ class TestH5A(unittest.TestCase):
h5a.close(aid)
self.assert_(not self.is_attr(aid))
- self.assertRaises(TypeError, h5a.close, -1)
+ self.assertRaises(ValueError, h5a.close, -1)
def test_delete(self):
fid, filename = getcopy(HDFNAME)
@@ -103,7 +103,7 @@ class TestH5A(unittest.TestCase):
self.assert_(not h5a.py_exists(obj, ATTRIBUTES_ORDER[0]))
deletecopy(fid, filename)
- self.assertRaises(TypeError, h5a.delete, -1, "foo")
+ self.assertRaises(ValueError, h5a.delete, -1, "foo")
# === Attribute I/O =======================================================
@@ -125,7 +125,7 @@ class TestH5A(unittest.TestCase):
h5a.close(aid)
- self.assertRaises(TypeError, h5a.read, -1, arr_holder)
+ self.assertRaises(ValueError, h5a.read, -1, arr_holder)
# h5a.write is done by test_create_write
@@ -134,7 +134,7 @@ class TestH5A(unittest.TestCase):
def test_get_num_attrs(self):
n = h5a.get_num_attrs(self.obj)
self.assertEqual(n, len(ATTRIBUTES))
- self.assertRaises(H5Error, h5a.get_num_attrs, -1)
+ self.assertRaises(ValueError, h5a.get_num_attrs, -1)
def test_get_name(self):
@@ -144,7 +144,7 @@ class TestH5A(unittest.TestCase):
self.assertEqual(supposed_name, name)
h5a.close(aid)
- self.assertRaises(TypeError, h5a.get_name, -1)
+ self.assertRaises(ValueError, h5a.get_name, -1)
def test_get_space(self):
@@ -156,7 +156,7 @@ class TestH5A(unittest.TestCase):
h5s.close(sid)
h5a.close(aid)
- self.assertRaises(TypeError, h5a.get_space, -1)
+ self.assertRaises(ValueError, h5a.get_space, -1)
def test_get_type(self):
@@ -168,7 +168,7 @@ class TestH5A(unittest.TestCase):
h5t.close(tid)
h5a.close(aid)
- self.assertRaises(TypeError, h5a.get_type, -1)
+ self.assertRaises(ValueError, h5a.get_type, -1)
def test_iterate(self):
@@ -201,14 +201,14 @@ class TestH5A(unittest.TestCase):
h5a.iterate(self.obj, iterate_two, namelist, 1)
self.assertEqual(namelist, ATTRIBUTES_ORDER[1:3])
- self.assertRaises(TypeError, h5a.iterate, -1, iterate_two, namelist)
+ self.assertRaises(ValueError, h5a.iterate, -1, iterate_two, namelist)
# === Python extensions ===================================================
def test_py_listattrs(self):
self.assertEqual(h5a.py_listattrs(self.obj), ATTRIBUTES_ORDER)
- self.assertRaises(TypeError, h5a.py_listattrs, -1)
+ self.assertRaises(ValueError, h5a.py_listattrs, -1)
def test_py_shape(self):
@@ -217,7 +217,7 @@ class TestH5A(unittest.TestCase):
retshape = h5a.py_shape(aid)
self.assertEqual(retshape, shape)
h5a.close(aid)
- self.assertRaises(TypeError, h5a.py_shape, -1)
+ self.assertRaises(ValueError, h5a.py_shape, -1)
def test_py_dtype(self):
@@ -225,7 +225,7 @@ class TestH5A(unittest.TestCase):
aid = h5a.open_name(self.obj, name)
self.assertEqual(h5a.py_dtype(aid),dt)
h5a.close(aid)
- self.assertRaises(TypeError, h5a.py_dtype, -1)
+ self.assertRaises(ValueError, h5a.py_dtype, -1)
def test_py_get(self):
@@ -234,7 +234,7 @@ class TestH5A(unittest.TestCase):
arr_returned = h5a.py_get(self.obj, name)
self.assert_(all(arr_returned == arr_reference),
errstr(arr_reference, arr_returned))
- self.assertRaises(TypeError, h5a.py_get, -1, "foo")
+ self.assertRaises(ValueError, h5a.py_get, -1, "foo")
def test_py_set(self):
@@ -249,7 +249,7 @@ class TestH5A(unittest.TestCase):
h5g.close(obj)
deletecopy(fid, filename)
- self.assertRaises(TypeError, h5a.py_set, -1, "foo", arr_reference)
+ self.assertRaises(ValueError, h5a.py_set, -1, "foo", arr_reference)
def test_py_exists(self):
diff --git a/h5py/utils.pxd b/h5py/utils.pxd
index 78e5d04..aee1676 100644
--- a/h5py/utils.pxd
+++ b/h5py/utils.pxd
@@ -16,14 +16,24 @@ from numpy cimport ndarray
cdef extern from "utils_low.h":
+ # Python to HDF5 complex conversion
hid_t create_ieee_complex64(char byteorder, char* real_name, char* img_name)
hid_t create_ieee_complex128(char byteorder, char* real_name, char* img_name)
- hsize_t* tuple_to_dims(object tpl)
- object dims_to_tuple(hsize_t* dims, hsize_t rank)
+ # Tuple conversion
+ int convert_tuple(object tpl, hsize_t *dims, hsize_t rank) except -1
+ object convert_dims(hsize_t* dims, hsize_t rank)
+
+ # Numpy array validation
int check_numpy_read(ndarray arr, hid_t space_id)
int check_numpy_write(ndarray arr, hid_t space_id)
+ # Memory handling
void* emalloc(size_t size) except? NULL
+ void efree(void* ptr)
+
+# === Custom API ==============================================================
+
+cdef int require_tuple(object tpl, int none_allowed, int size, char* name) except -1
diff --git a/h5py/utils.pyx b/h5py/utils.pyx
new file mode 100644
index 0000000..70b468d
--- /dev/null
+++ b/h5py/utils.pyx
@@ -0,0 +1,18 @@
+from python cimport PyTuple_Check
+
+cdef int require_tuple(object tpl, int none_allowed, int size, char* name) except -1:
+ # Ensure that tpl is in fact a tuple, or None if none_allowed is nonzero.
+ # If size >= 0, also ensure that the length matches.
+
+ if (tpl is None and none_allowed) or \
+ ( PyTuple_Check(tpl) and (size < 0 or len(tpl) == size)):
+ return 1
+
+ nmsg = ""
+ smsg = ""
+ if size >= 0:
+ smsg = " of size %d" % size
+ if none_allowed:
+ nmsg = " or None"
+
+ raise ValueError("%s must be a tuple%s%s." % (name, smsg, nmsg))
diff --git a/h5py/utils_low.c b/h5py/utils_low.c
index 1ecca26..983b189 100644
--- a/h5py/utils_low.c
+++ b/h5py/utils_low.c
@@ -26,8 +26,8 @@
/* Wrapper for malloc(size) with the following behavior:
1. Always returns NULL for emalloc(0)
- 2. Raises RuntimeError for emalloc(size<0)
- 3. Raises RuntimeError if allocation fails (malloc returns NULL)
+ 2. Raises RuntimeError for emalloc(size<0) and returns NULL
+ 3. Raises RuntimeError if allocation fails and returns NULL
*/
void* emalloc(size_t size){
@@ -46,10 +46,17 @@ void* emalloc(size_t size){
return retval;
}
+/* Counterpart to emalloc. For the moment, just a wrapper for free().
+*/
+void efree(void* ptr){
+ free(ptr);
+}
+
/* Convert an hsize_t array to a Python tuple of long ints.
- Returns None on failure
+ Returns NULL on failure, and raises an exception (either propagates
+ an exception from the conversion, or raises RuntimeError).
*/
-PyObject* dims_to_tuple(hsize_t* dims, hsize_t rank) {
+PyObject* convert_dims(hsize_t* dims, hsize_t rank) {
PyObject* tpl;
PyObject* plong;
@@ -66,33 +73,34 @@ PyObject* dims_to_tuple(hsize_t* dims, hsize_t rank) {
PyTuple_SET_ITEM(tpl, i, plong); /* steals reference */
}
- Py_INCREF(tpl);
return tpl;
err:
Py_XDECREF(tpl);
- Py_INCREF(Py_None);
- return Py_None;
+ if(!PyErr_Occurred()){
+ PyErr_SetString(PyExc_RuntimeError, "Failed to convert hsize_t array to tuple.");
+ }
+ return NULL;
}
-/* Convert a Python tuple to a malloc'ed hsize_t array
- Returns NULL on failure
+/* Convert a Python tuple to an hsize_t array. You must allocate
+ the array yourself and pass both it and the size to this function.
+ Returns 0 on success, -1 on failure and raises an exception.
*/
-hsize_t* tuple_to_dims(PyObject* tpl){
+int convert_tuple(PyObject* tpl, hsize_t *dims, hsize_t rank_in){
+ PyObject* temp = NULL;
int rank;
- hsize_t* dims;
- PyObject* temp;
int i;
- dims = NULL;
- temp = NULL;
if(tpl == NULL) goto err;
if(!PyTuple_Check(tpl)) goto err;
rank = (int)PyTuple_GET_SIZE(tpl);
-
- dims = (hsize_t*)malloc(sizeof(hsize_t)*rank);
+ if(rank != rank_in) {
+ PyErr_SetString(PyExc_RuntimeError, "Allocated space does not match tuple length");
+ goto err;
+ }
for(i=0; i<rank; i++){
temp = PyTuple_GetItem(tpl, i);
@@ -108,11 +116,13 @@ hsize_t* tuple_to_dims(PyObject* tpl){
goto err;
}
- return dims;
+ return 0;
err:
- if(dims!=NULL) free(dims);
- return NULL;
+ if(!PyErr_Occurred()){
+ PyErr_SetString(PyExc_ValueError, "Illegal argument (must be a tuple of numbers).");
+ }
+ return -1;
}
/* The functions
diff --git a/h5py/utils_low.h b/h5py/utils_low.h
index 53dab9e..72c3108 100644
--- a/h5py/utils_low.h
+++ b/h5py/utils_low.h
@@ -27,12 +27,14 @@
hid_t create_ieee_complex64(const char byteorder, const char* real_name, const char* img_name);
hid_t create_ieee_complex128(const char byteorder, const char* real_name, const char* img_name);
-
-hsize_t* tuple_to_dims(PyObject* tpl);
-PyObject* dims_to_tuple(hsize_t* dims, hsize_t rank);
+int convert_tuple(PyObject* tpl, hsize_t *dims, hsize_t rank);
+PyObject* convert_dims(hsize_t* dims, hsize_t rank);
int check_numpy_read(PyArrayObject* arr, hid_t space_id);
int check_numpy_write(PyArrayObject* arr, hid_t space_id);
+void* emalloc(size_t size);
+void efree(void* ptr);
+
#endif
diff --git a/setup.py b/setup.py
index 838b4c3..2c0e01c 100644
--- a/setup.py
+++ b/setup.py
@@ -178,7 +178,7 @@ ext_exten = '.pyx'
# Pyrex extension modules
pyx_modules = ['h5e', 'h5' , 'h5f', 'h5g', 'h5s', 'h5t',
- 'h5d', 'h5a', 'h5p', 'h5z', 'h5i', 'h5r']
+ 'h5d', 'h5a', 'h5p', 'h5z', 'h5i', 'h5r', 'utils']
pyx_src_path = 'h5py'
pyx_extra_src = ['utils_low.c'] # C source files required for Pyrex code
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/debian-science/packages/h5py.git
More information about the debian-science-commits
mailing list