Every scientist who has outgrown np.save eventually meets the same wall. NumPy arrays live in memory and die with the process; the moment your data is tens of gigabytes, or several processes need to write it at once, or a colleague on another continent needs to read one slice without downloading everything, you need a real file format with real semantics: partial reads, chunked compression, metadata, and concurrent access. HDF5 has provided those semantics for decades, and h5py is the Python layer that makes them feel like NumPy.
The catch is that the comfort is an illusion — a carefully constructed one. f["data"][0:1000] looks like dict access plus slicing, but underneath, a C library is being driven through property lists, dataspaces, and identifier registries. When a read suddenly gets slow, when a file refuses to open because of locking, or when compression behaves unexpectedly, Stack Overflow answers stop working and you need the actual architecture. That is exactly what this tour provides: the h5py tree at version 3.17.0 (master), read file by file, with every symbol pinned to a real line.
The repository splits cleanly into two worlds. The Cython layer — a couple dozen h5*.pyx modules like h5d.templ.pyx, h5p.templ.pyx, and h5s.pyx — wraps raw HDF5 calls with error translation and reference counting. The high-level layer under h5py/_hl/ builds the familiar object model (File, Group, Dataset, AttributeManager) on top of those bindings. The overview below shows how import-time wiring connects them; the detail diagram goes one level deeper into selections, filters, and the generated binding core.
Overview of h5py: the public package re-exports the high-level object model, which drives the Cython core through generated HDF5 wrappers.
Reading the overview from left to right:
_register_lzf, L52 — importing h5py immediately registers the bundled LZF compression filter, before any file is opened.File, L289 — the class users touch first is literallyclass File(Group): an open HDF5 file is just a root group with extra lifecycle._drivers, L65 — the driver registry mapssec2,stdio,core,family,mpio,fileobj, andsplitto property-list setters, withros3anddirectadded only when the build supports them.Dataset.__getitem__, L893 — NumPy-style slicing enters here and is translated into HDF5 selections before any data moves.select, L19 — the dispatcher that turns arbitrary index tuples intoPointSelection,SimpleSelection, orFancySelectionobjects.fill_dcpl, L148 — compression kwargs become entries in a dataset creation property list;DEFAULT_GZIP = 4sits at L56 of the same file.DatasetID, L170 — the Cython owner of an HDF5 dataset identifier, includingwrite_direct_chunk(L486) for raw chunk injection.set_fapl_mpio, L1510 — MPI parallel I/O is configured through this property-list method; thempiodriver infiles.pyrefuses to run when the build lacks it.defs.pyx wrappers, L1 — the lowest-level bindings are not hand-written:api_gen.pygeneratesdefs.pyx,defs.pxd, and_hdf5.pxdfrom an annotated function table.
The detail diagram expands each region into its real modules — including the lock machinery in _objects.templ.pyx, the filter chain ending in the vendored LZF C sources, and the property-list class family that mirrors HDF5’s H5P taxonomy.
Detailed view: 33 modules across the high-level API, selection engine, filter chain, Cython core, and generated binding layer.
The two-layer split is the whole design
h5py’s architecture answers one question: how do you give Python a 1990s C API without dragging its complexity upward? The Cython layer keeps each h5*.pyx module a thin mirror of one HDF5 header. GroupID, L251, AttrID, L304, and SpaceID, L119 all subclass a single reference-counted wrapper, ObjectID, L178, which owns the raw hid_t and decrements it deterministically.
Thread safety is solved in the same layer. HDF5 is not generally thread-safe, so h5py serializes calls with a global re-entrant lock: _objects.templ.pyx declares phil = _phil, L51 — a FastRLock, with a pure-Python BogoLock fallback — and a with_phil, L53 decorator wraps every public low-level function. The name is a joke that stuck (the Philosophers’ lock), but the mechanism is serious: without it, concurrent reads from threads would corrupt library state.
The high-level layer is deliberately thicker. _hl/base.py provides HLObject, L275 plus mapping views, while _hl/group.py and _hl/dataset.py implement the dict and array protocols. Group, L76 subclasses MutableMappingHDF5, so f["key"] = arr and iteration behave like a normal Python mapping even though every operation crosses into C.
Selections: NumPy indexing compiled to dataspaces
The trickiest translation in h5py is indexing. NumPy slices can be integers, ranges, steps, ellipses, None, boolean arrays, or integer arrays; HDF5 only understands hyperslabs and point lists. _hl/selections.py does the semantic translation: FancySelection, L312 handles orthogonal array indexing, and PointSelection, L166 handles scattered coordinates, both producing a SpaceID that the C layer can use directly.
A second file exists purely for speed. _hl/selections2.py implements read_selections_scalar, L46, a fast path for scalar and simple reads that avoids building full selection objects. And when even that is too slow, the newest layer is native code: _selector.pyx defines Selector, L40 and a Reader, L319 that extract straight into typed memoryviews, plus a public MultiBlockSlice, L404 type for strided multi-block reads that HDF5 hyperslabs express naturally but Python syntax does not.
The payoff is that datasets behave like lazy NumPy arrays. Reading dset[::2, 5:10] never materializes the whole array; only the requested hyperslab crosses the C boundary. Libraries such as Dask exploit exactly this behavior — dask treats h5py datasets as chunked arrays and issues block-wise reads through this same selection machinery.
Filters: gzip, LZF, and the plugin door
Compression is configured through dataset creation property lists, and _hl/filters.py is the translator. _gen_filter_tuples, L59 probes the library at import time to learn which filters can encode and decode, while Gzip, L141 is a FilterRefBase subclass whose instances work both as compression= kwargs and as mapping objects.
One filter ships inside the repo itself. The lzf/ directory contains a vendored LZF implementation whose header declares H5PY_FILTER_LZF 32000 — a filter ID registered with the HDF Group back in 2009, revision 4 — and h5py registers it through _register_lzf, L133 during package import. This is why h5py files can use fast, checksum-free compression without third-party plugins, while heavier codecs (szip, zstd) require either the library build or a dynamic plugin.
The plugin door stays open for everyone else. register_filter, L103 accepts the raw address of an H5Z_class2_t structure, letting users load dynamically-linked filter plugins with ctypes. Format interoperability beyond HDF5 is a different story — the columnar ecosystem standardized on Arrow instead, whose memory-format-first philosophy contrasts with HDF5’s file-first one; the trade-offs are visible in arrow’s source as well.
From 486 function rows to typed Cython wrappers
The build system is the least visible but most instructive part of the tree. Binding every HDF5 call by hand would be unmanageable, so h5py generates the bottom layer. h5py/api_functions.txt contains 486 annotated rows — return type, name, signature, and flags for MPI, ROS3, direct-VFD, GIL release, and minimum HDF5 version — which api_gen.py (see its Line class documentation) compiles into three files: _hdf5.pxd (raw extern declarations), defs.pxd, and defs.pyx (Cython “error wrappers” that turn HDF5 error stacks into Python exceptions).
The extension list in setup_build.py names 24 Cython modules (defs, _errors, _objects, _proxy, h5fd, h5z, h5, h5i, h5r, utils, _selector, _conv, h5t, h5s, h5p, h5d, h5a, h5f, h5g, h5l, h5o, h5ds, h5ac, h5pl), plus _npystrings built only under NumPy 2, and the two templated type modules. Compilation links hdf5 and hdf5_hl, defines H5_USE_110_API to pin the function surface, and opts into the stable ABI by appending the Py_LIMITED_API macro — one reason manylinux wheels work across CPython versions.
Templates explain the odd .templ.pyx suffix. Files like h5p.templ.pyx are run through Cython’s Tempita preprocessor to stamp out the property-list family: PropID, L153 heads a hierarchy through PropFCID (L285), PropDCID (L449), and PropFAID (L1059), each mirroring one H5P class from the C API. Even versioning is defensive: version.py carries a 3.17.0 dev tuple and an _hdf5_abi_compatible check that demands an exact match for HDF5 1.x but tolerates newer same-major libraries from 2.x onward — a direct response to HDF5 2.0’s ABI reset.
Drivers and parallel I/O
The _drivers table is where I/O strategies live, and it doubles as a plugin registry via register_driver. The defaults cover ordinary disk (sec2), streaming (stdio), in-memory (core with optional backing store), multi-file (family), and split metadata/raw layouts (split). Two optional entries reveal the scale ambitions: ros3 reads HDF5 directly from S3-compatible object stores, and mpio turns one file into a coordinated target for an MPI communicator — _set_fapl_mpio, L50 imports mpi4py lazily and fails with a clear message when the build lacks MPI.
Direct chunk access completes the high-performance story: DatasetID.write_direct_chunk and read_direct_chunk bypass the selection layer entirely and hand raw, already-filtered chunk buffers to the library, which is what multi-writer simulation codes and streaming writers use. Between the drivers table, chunk-level primitives, and the global lock, h5py encodes a decade of pragmatic decisions about what “parallel” means for a Python library.
Honest Limits
The design carries real costs. The global Enjoyed this post? Never miss out on future posts by following us phil lock serializes all low-level calls, so h5py threads never run HDF5 work concurrently — true parallelism requires MPI builds or separate processes, and the repo’s own examples/threading_example.py exists mostly to demonstrate what will not scale. Partial-clone-friendly browsing is another constraint: the heavy logic lives in generated files (defs.pyx) and Tempita-expanded modules that do not exist in a fresh checkout, so reading h5d.templ.pyx tells you less than the docs suggest about final call behavior. The mapping illusion also leaks — Group iteration order depends on creation-order tracking flags, File locking interacts with OS-level semantics that differ per driver, and vlen/string dtypes force copies at the NumPy boundary. Finally, this tour pins the master tree at version 3.17.0-dev; line numbers move as the project evolves, so treat them as a snapshot, not a contract.