Skip to content

brainhops.io.common.hdf5

Shared machinery for formats stored in HDF5 files.

ITK .h5 transforms and BIDS X5 files both keep their transforms under a root TransformGroup, so only their content tells them apart. A format therefore only says how to recognise and decode an open h5py.File, and the classes of this module handle paths, streams, bytes and lazy datasets. h5py is optional, so this module is only imported by the formats that need it.

Attributes

H5Like module-attribute

H5Like = BinaryIO | PathLike | str | h5py.File

Anything an HDF5 format can be read from or written to.

Classes

H5ArrayProxy magic

H5ArrayProxy(file: Path | File, path: str)

Bases: StoredProxy

An HDF5 dataset that can be read after its file was closed, by reopening the file on demand.

Indexing the array returns another lazy array (see StoredProxy), and converting that array reads only the selected part of the dataset. That lazy array reads through this one, so a file that this array keeps open is used by every index of it.

Parameters:

Name Type Description Default
file Path | File

The HDF5 file, by its path or as an open file. A file name given as a string or a path-like object is converted to a [Path][brainhops._core.path.Path].

required
path str

The path of the dataset in the file.

required

Attributes

root property

The proxy itself, since it reads its values from its storage.

ndim property
ndim: int

The number of dimensions.

size property
size: int

The number of values.

itemsize property
itemsize: int

The number of bytes that one value takes once it is read.

nbytes property
nbytes: int

The number of bytes that the values take once they are read.

T property

The proxy with its axes in reverse order.

file instance-attribute
file: Annotated[Path | File, ConvertTo(as_path_or_stream)]

The HDF5 file, by its path or as an open file. A file name given as a string or a path-like object is converted to a [Path][brainhops._core.path.Path].

path instance-attribute
path: str

The path of the dataset in the file.

shape property
shape: tuple[int, ...]

The shape of the dataset.

dtype property
dtype: dtype

The dtype of the dataset.

chunks property
chunks: tuple | None

The shape of a chunk, or None if the dataset is not chunked.

Methods:

__getitem__
__getitem__(index: Any) -> ArrayProxy

Return a proxy that selects a part of the values.

The result is an IndexedProxy of this proxy, or this proxy itself when the index selects every value in order.

Raises:

Type Description
IndexError

If an index is out of bounds, if there are more indices than dimensions, or if the index selects points rather than a box.

TypeError

If an element of the index has an unsupported type.

transpose
transpose(*axes: Any) -> StoredProxy

Return the proxy with its axes in another order.

The result is a PermutedProxy of this proxy, or this proxy itself when the permutation changes nothing.

Parameters:

Name Type Description Default
*axes int or sequence of int

The permutation, given as integers or as one sequence. Axis i of the result is axis axes[i] of the proxy.

()

Returns:

Type Description
StoredProxy

The transposed proxy.

Raises:

Type Description
ValueError

If the axes are not a permutation of the axes of the proxy.

reshape
reshape(
    *shape: Any, order: str = "C", copy: bool | None = None
) -> ArrayProxy

Return a proxy of the values in another shape, as NumPy does.

Nothing is read. A reshape that only adds or removes axes of length one is an index of the proxy. A strided proxy whose values NumPy could reshape without copying them gives another strided proxy (see [StridedProxy][brainhops._core.strided.StridedProxy]). Any other reshape gives a ReshapedProxy, which reads the values that a selection needs, and at most a few extra rows.

Parameters:

Name Type Description Default
*shape int or sequence of int

The new shape, given as integers or as one sequence. One length may be -1, and it is then inferred from the others.

()
order (C, F)

The order in which the values are read and placed: the last axis varies fastest in C order, and the first one in Fortran order.

"C"
copy bool

Accepted for compatibility with np.reshape. A proxy never copies values, since it reads them when they are needed.

None

Returns:

Type Description
ArrayProxy

The reshaped proxy.

Raises:

Type Description
ValueError

If the new shape does not hold as many values as the proxy, or order is neither "C" nor "F".

__array__
__array__(
    dtype: Any = None, copy: bool | None = None
) -> ndarray

Read all the values.

Raises:

Type Description
ValueError

If copy is False, because reading values cannot be done without making them.

to_numpy
to_numpy() -> ndarray

Read the values of the proxy into a NumPy array.

Returns:

Type Description
ndarray

The values.

to_cupy
to_cupy(device: DeviceLike = None) -> ArrayProtocol

Read the values of the proxy into a CuPy array on the GPU.

Returns:

Type Description
ndarray

The values.

Raises:

Type Description
ImportError

If CuPy is not installed.

to_backend
to_backend(
    backend: BackendLike | None = None,
) -> ArrayProtocol

Convert the proxy as a backend setting says.

The settings are described in brainhops.backends. Under "native", and under "auto", a proxy of at most the threshold of "auto" is read with NumPy and a larger one becomes a Dask array. A Dask array has the blocks that to_dask gives, and reading it reads only the blocks that it needs.

Parameters:

Name Type Description Default
backend str or module

The setting. By default, the current setting is used.

None

Returns:

Type Description
array

A NumPy, CuPy or Dask array.

Raises:

Type Description
ImportError

If a package that the setting needs is not installed.

__array_ufunc__
__array_ufunc__(
    ufunc: ufunc, method: str, *inputs: Any, **kwargs: Any
) -> Any

Apply a universal function of NumPy, such as np.add.

The operators of Python, such as proxy + 1, call this method too. The proxies among the operands are converted to the backend of the computation, and so are the arrays of other backends. When the computation writes into the arrays given as out, it runs in their backend. Otherwise, the backend is the one that promote_backends chooses for the operands.

Parameters:

Name Type Description Default
ufunc ufunc

The universal function.

required
method str

The method of the function, such as "__call__" or "reduce".

required
*inputs Any

The operands.

()
**kwargs Any

The options of the function.

{}

Returns:

Type Description
Any

The result, or NotImplemented when an operand is of a type that the proxy does not know.

Raises:

Type Description
TypeError

If a proxy is given as out.

__array_function__
__array_function__(
    func: Callable,
    types: Collection[type],
    args: tuple[Any, ...],
    kwargs: dict[str, Any],
) -> Any

Apply a function of NumPy, such as np.concatenate.

When the computation runs in NumPy, the implementation of NumPy receives the proxies themselves. It asks them for what it needs, so that np.shape reads nothing, np.transpose and np.reshape return proxies, and np.mean calls the method of the proxy, which reads the values. In any other backend, the proxies and the arrays of other backends are converted to the backend that promote_backends chooses for them, and the function of that backend runs.

Parameters:

Name Type Description Default
func callable

The function of NumPy.

required
types collection of type

The types of the operands that define __array_function__.

required
args tuple

The positional arguments of the call.

required
kwargs dict

The keyword arguments of the call.

required

Returns:

Type Description
Any

The result, or NotImplemented when an operand is of a type that the proxy does not know.

open
open() -> File

Open the HDF5 file, or reuse the open one, and return it.

close
close() -> None

Close the HDF5 file if this array opened it.

to_dataset
to_dataset(
    file: H5Like | None = None, keep_open: bool = False
) -> Dataset

Return the whole h5py.Dataset, opening the file if needed.

With keep_open, a file opened by name stays open until close.

to_array
to_array(**kwargs) -> ndarray

Read the values of the array into a NumPy array.

to_dask
to_dask(
    *, keep_open: bool = False, **kwargs
) -> ArrayProtocol

Wrap the array in a dask array that reads its chunks lazily.

With keep_open, the chunks are read from the open dataset; otherwise the file is reopened for each chunk.

Hdf5Reader

Bases: BinaryFileReader

A mixin that reads a format stored in HDF5.

A concrete format implements the class methods sniff_h5 and from_h5, which take an open h5py.File, and the mixin routes paths, streams and bytes to them. A path is handed to h5py by name, so that a lazily read dataset can reopen the file long after parsing.

Attributes

EXTENSIONS class-attribute
EXTENSIONS: tuple[str, ...] = ()

File extensions that the format handles, such as (".mgh", ".mgz").

A matching extension keeps the format among the candidates even if its sniffer declines, and the extension match is the next ranking criterion after the sniffer score. The longest matching extension wins, so .note.txt beats .txt. Every format may be compressed, so the extensions leave out compression suffixes: a name that ends with .gz, .bz2 or .xz also matches the extensions of the name without that suffix, and x.nii.gz matches .nii. An extension that implies compression without such a suffix, such as .mgz, is listed.

PREFIXES class-attribute
PREFIXES: tuple[str, ...] = ()

Required file name prefixes, such as ("y_", "iy_").

An empty tuple means that any name is accepted. When prefixes are declared, a file name matches the format only if it starts with one of them, and a format with a matching prefix is more specific and wins ties. Extensions and prefixes are declared separately, and every prefix combines with every extension, as file naming conventions usually do: the four names of SPM deformation fields are {y_, iy_} times {.nii, .nii.gz}.

PRIORITY class-attribute
PRIORITY: int = 0

Tie-breaker used only when specificity cannot decide.

The higher value wins. The priority should stay at 0 unless two parsers genuinely collide.

Methods:

sniff classmethod
sniff(
    file: FileOrContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score how confidently a file or its content is of this type.

A path is sniffed with sniff_filename, an open file with sniff_fileobj, and binary content with sniff_bytes.

Parameters:

Name Type Description Default
file FileOrContentLike

The file or its content.

required
error bool or type of Exception

If not false, raise when the input cannot be sniffed: True raises the default error, and an exception class raises that class.

False
**kwargs Any

Parser options.

{}

Returns:

Type Description
float

The confidence, between 0 and 1. An unsupported input scores zero.

sniff_content classmethod
sniff_content(
    content: ContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for bytes, text, or lines.

sniff_bytes classmethod
sniff_bytes(
    content: BinaryContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for binary content.

Compressed content is decompressed first. The content is then wrapped in an io.BytesIO and scored with sniff_fileobj, so that a class that scores a stream also scores bytes. If that method only reads the stream back into bytes, as the default does, the content would come back to this method, which then raises instead.

Raises:

Type Description
SnifferNotImplementedError

If neither this method nor sniff_fileobj is implemented.

sniff_text classmethod
sniff_text(
    text: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for text.

The text is split into lines and passed to sniff_lines.

sniff_lines classmethod
sniff_lines(
    lines: Iterable[str],
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for an iterable of lines.

The first line is passed to sniff_line.

sniff_line classmethod
sniff_line(
    line: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for a single line.

Raises:

Type Description
SnifferNotImplementedError

In the base class, which cannot sniff a line.

load classmethod
load(other: FileOrContentLike, **kwargs) -> Self

Read an object from a path, an open file, or binary content.

Paths and open files are read with from_file, binary content with from_bytes, and a SourceSpec with from_spec. A str is always a path, whether or not the file exists, so text held in memory must be read with from_text or from_content. The default from_filename, from_fileobj and from_bytes decompress a file or content that gzip, bzip2 or xz compresses, so that a format that does not override them reads compressed files too.

Raises:

Type Description
ParserExistsError

If the path names a file that does not exist.

ParserTypeError

If the input is of another type.

from_spec classmethod
from_spec(spec: SourceSpec, **kwargs) -> Self

Read the file named by a specification without hints or options.

Raises:

Type Description
TypeError

If the specification has hints or options, which only a dispatcher can apply.

from_content classmethod
from_content(content: ContentLike, **kwargs) -> Self

Read an object from bytes, text, or lines.

from_bytes classmethod
from_bytes(content: BinaryContentLike, **kwargs) -> Self

Read an object from binary content.

Compressed content is decompressed first. If the class implements from_fileobj itself, the content is wrapped in an io.BytesIO and read with that method. Otherwise, this method raises, because the default from_fileobj would pass the content back to from_bytes and the fallback would recurse. An override that only forwards to super().from_fileobj should be marked with passthrough_from_fileobj. If such an override is not marked, the loop is still detected when this method is entered again for the same class.

Raises:

Type Description
ParserNotImplementedError

If neither this method nor from_fileobj is implemented.

from_text classmethod
from_text(text: str, **kwargs) -> Self

Read an object from text.

The text is split into lines and passed to from_lines.

from_lines classmethod
from_lines(lines: Iterable[str], **kwargs) -> Self

Read an object from an iterable of lines.

The first line is passed to from_line.

from_line classmethod
from_line(line: str, **kwargs) -> Self

Read an object from a single line.

Raises:

Type Description
ParserNotImplementedError

In the base class, which cannot read a line.

sniff_h5 classmethod
sniff_h5(
    h5file: File, error: bool | Type[Exception] = False
) -> float

Return the confidence that an open HDF5 file is of this format.

A concrete format implements this method.

Parameters:

Name Type Description Default
h5file File

The file, open for reading.

required
error bool or type[Exception]

Whether to raise an error when the content is not of this format. With True, the error is a SnifferContentError, and an exception class is raised instead when one is given.

False

Returns:

Type Description
float

The confidence that the content is of this format.

Raises:

Type Description
NotImplementedError

If the format does not implement it.

from_h5 classmethod
from_h5(h5file: File, **kwargs) -> Self

Build an object from an open HDF5 file.

A concrete format implements this method.

Parameters:

Name Type Description Default
h5file File

The file, open for reading.

required
**kwargs Any

The options of the format.

{}

Returns:

Type Description
Self

The object.

Raises:

Type Description
NotImplementedError

If the format does not implement it.

sniff_file classmethod
sniff_file(
    file: H5Like,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score a path, an open HDF5 file or a binary stream.

Parameters:

Name Type Description Default
file path-like, h5py.File or file object

The content to test.

required
error bool or type[Exception]

Whether to raise an error when the content is not of this format. With True, the error is a SnifferContentError, and an exception class is raised instead when one is given.

False
**kwargs Any

Options passed to sniff_filename or sniff_fileobj.

{}

Returns:

Type Description
float

The confidence that the content is of this format.

Raises:

Type Description
SnifferError

If the content is not of this format and error is True.

sniff_filename classmethod
sniff_filename(
    filename: str | PathLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score the HDF5 file at a path.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
error bool or type[Exception]

Whether to raise an error when the content is not of this format. With True, the error is a SnifferContentError, and an exception class is raised instead when one is given.

False
**kwargs Any

Options passed to sniff_fileobj when h5py cannot open the path by name.

{}

Returns:

Type Description
float

The confidence that the content is of this format.

Raises:

Type Description
SnifferExistsError

If the path does not exist and error is True.

SnifferContentError

If the file is not of this format and error is True.

sniff_fileobj classmethod
sniff_fileobj(
    file: IO,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score an open, seekable binary stream.

The position of the stream is restored.

Parameters:

Name Type Description Default
file file object

The stream to test, open in binary mode.

required
error bool or type[Exception]

Whether to raise an error when the content is not of this format. With True, the error is a SnifferContentError, and an exception class is raised instead when one is given.

False
**kwargs Any

Ignored.

{}

Returns:

Type Description
float

The confidence that the content is of this format.

Raises:

Type Description
SnifferContentError

If the stream is not of this format and error is True.

from_file classmethod
from_file(file: H5Like, **kwargs) -> Self

Build an object from a path, a binary stream or an open HDF5 file.

The keyword arguments are the options of the format, which from_h5 receives. A file that this method opens is closed once it is read, so a format that reads a dataset later opens the file again by its name.

Parameters:

Name Type Description Default
file path-like, h5py.File or file object

The content to read.

required
**kwargs Any

The options of the format.

{}

Returns:

Type Description
Self

The object.

from_filename classmethod
from_filename(filename: str | PathLike, **kwargs) -> Self

Build an object from the HDF5 file at a path.

The file is opened by name, so that a dataset that is read later can open the file again by the same name.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
**kwargs Any

The options of the format.

{}

Returns:

Type Description
Self

The object.

Raises:

Type Description
ParserExistsError

If the path does not exist.

from_fileobj classmethod
from_fileobj(file: IO, **kwargs) -> Self

Build an object from an open, seekable binary stream.

The position of the stream is restored.

Parameters:

Name Type Description Default
file file object

The stream, open in binary mode.

required
**kwargs Any

The options of the format.

{}

Returns:

Type Description
Self

The object.

Hdf5ReaderWriter

Bases: Hdf5Reader, BinaryFileWriter

A mixin that reads and writes a format stored in HDF5.

The format also implements to_h5, which fills a new, empty HDF5 file.

Attributes

EXTENSIONS class-attribute
EXTENSIONS: tuple[str, ...] = ()

File extensions that the format handles, such as (".mgh", ".mgz").

A matching extension keeps the format among the candidates even if its sniffer declines, and the extension match is the next ranking criterion after the sniffer score. The longest matching extension wins, so .note.txt beats .txt. Every format may be compressed, so the extensions leave out compression suffixes: a name that ends with .gz, .bz2 or .xz also matches the extensions of the name without that suffix, and x.nii.gz matches .nii. An extension that implies compression without such a suffix, such as .mgz, is listed.

PREFIXES class-attribute
PREFIXES: tuple[str, ...] = ()

Required file name prefixes, such as ("y_", "iy_").

An empty tuple means that any name is accepted. When prefixes are declared, a file name matches the format only if it starts with one of them, and a format with a matching prefix is more specific and wins ties. Extensions and prefixes are declared separately, and every prefix combines with every extension, as file naming conventions usually do: the four names of SPM deformation fields are {y_, iy_} times {.nii, .nii.gz}.

PRIORITY class-attribute
PRIORITY: int = 0

Tie-breaker used only when specificity cannot decide.

The higher value wins. The priority should stay at 0 unless two parsers genuinely collide.

Methods:

save
save(file: FileLike, **kwargs) -> None

Write the object to a path or an open file.

The method is named save rather than to because the data models that parsers are mixed into already use to for conversion, as in Transformation.to, which would shadow the writer.

to_fileobj
to_fileobj(file: IO, **kwargs) -> None

Write the object to a file object open for writing.

A binary format writes the result of to_bytes. A text format writes the result of to_text to a text stream, such as a file opened with "w" or an io.StringIO, and the result of to_bytes to any other stream, such as a file opened with "wb" or an io.BytesIO.

to_text
to_text(**kwargs) -> str

Return the text of the file.

The text is made of the lines of to_lines, each followed by a newline.

to_lines
to_lines(**kwargs) -> Iterator[str]

Return the lines of the file, without terminators.

The default implementation yields the result of to_line as the only line.

to_line
to_line(**kwargs) -> str

Return the single line that represents the object.

Raises:

Type Description
WriterNotImplementedError

In the base class, which cannot write a line.

sniff classmethod
sniff(
    file: FileOrContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score how confidently a file or its content is of this type.

A path is sniffed with sniff_filename, an open file with sniff_fileobj, and binary content with sniff_bytes.

Parameters:

Name Type Description Default
file FileOrContentLike

The file or its content.

required
error bool or type of Exception

If not false, raise when the input cannot be sniffed: True raises the default error, and an exception class raises that class.

False
**kwargs Any

Parser options.

{}

Returns:

Type Description
float

The confidence, between 0 and 1. An unsupported input scores zero.

sniff_file classmethod
sniff_file(
    file: H5Like,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score a path, an open HDF5 file or a binary stream.

Parameters:

Name Type Description Default
file path-like, h5py.File or file object

The content to test.

required
error bool or type[Exception]

Whether to raise an error when the content is not of this format. With True, the error is a SnifferContentError, and an exception class is raised instead when one is given.

False
**kwargs Any

Options passed to sniff_filename or sniff_fileobj.

{}

Returns:

Type Description
float

The confidence that the content is of this format.

Raises:

Type Description
SnifferError

If the content is not of this format and error is True.

sniff_filename classmethod
sniff_filename(
    filename: str | PathLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score the HDF5 file at a path.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
error bool or type[Exception]

Whether to raise an error when the content is not of this format. With True, the error is a SnifferContentError, and an exception class is raised instead when one is given.

False
**kwargs Any

Options passed to sniff_fileobj when h5py cannot open the path by name.

{}

Returns:

Type Description
float

The confidence that the content is of this format.

Raises:

Type Description
SnifferExistsError

If the path does not exist and error is True.

SnifferContentError

If the file is not of this format and error is True.

sniff_fileobj classmethod
sniff_fileobj(
    file: IO,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Score an open, seekable binary stream.

The position of the stream is restored.

Parameters:

Name Type Description Default
file file object

The stream to test, open in binary mode.

required
error bool or type[Exception]

Whether to raise an error when the content is not of this format. With True, the error is a SnifferContentError, and an exception class is raised instead when one is given.

False
**kwargs Any

Ignored.

{}

Returns:

Type Description
float

The confidence that the content is of this format.

Raises:

Type Description
SnifferContentError

If the stream is not of this format and error is True.

sniff_content classmethod
sniff_content(
    content: ContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for bytes, text, or lines.

sniff_bytes classmethod
sniff_bytes(
    content: BinaryContentLike,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for binary content.

Compressed content is decompressed first. The content is then wrapped in an io.BytesIO and scored with sniff_fileobj, so that a class that scores a stream also scores bytes. If that method only reads the stream back into bytes, as the default does, the content would come back to this method, which then raises instead.

Raises:

Type Description
SnifferNotImplementedError

If neither this method nor sniff_fileobj is implemented.

sniff_text classmethod
sniff_text(
    text: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for text.

The text is split into lines and passed to sniff_lines.

sniff_lines classmethod
sniff_lines(
    lines: Iterable[str],
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for an iterable of lines.

The first line is passed to sniff_line.

sniff_line classmethod
sniff_line(
    line: str,
    error: bool | Type[Exception] = False,
    **kwargs,
) -> float

Same as sniff, for a single line.

Raises:

Type Description
SnifferNotImplementedError

In the base class, which cannot sniff a line.

load classmethod
load(other: FileOrContentLike, **kwargs) -> Self

Read an object from a path, an open file, or binary content.

Paths and open files are read with from_file, binary content with from_bytes, and a SourceSpec with from_spec. A str is always a path, whether or not the file exists, so text held in memory must be read with from_text or from_content. The default from_filename, from_fileobj and from_bytes decompress a file or content that gzip, bzip2 or xz compresses, so that a format that does not override them reads compressed files too.

Raises:

Type Description
ParserExistsError

If the path names a file that does not exist.

ParserTypeError

If the input is of another type.

from_spec classmethod
from_spec(spec: SourceSpec, **kwargs) -> Self

Read the file named by a specification without hints or options.

Raises:

Type Description
TypeError

If the specification has hints or options, which only a dispatcher can apply.

from_file classmethod
from_file(file: H5Like, **kwargs) -> Self

Build an object from a path, a binary stream or an open HDF5 file.

The keyword arguments are the options of the format, which from_h5 receives. A file that this method opens is closed once it is read, so a format that reads a dataset later opens the file again by its name.

Parameters:

Name Type Description Default
file path-like, h5py.File or file object

The content to read.

required
**kwargs Any

The options of the format.

{}

Returns:

Type Description
Self

The object.

from_filename classmethod
from_filename(filename: str | PathLike, **kwargs) -> Self

Build an object from the HDF5 file at a path.

The file is opened by name, so that a dataset that is read later can open the file again by the same name.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
**kwargs Any

The options of the format.

{}

Returns:

Type Description
Self

The object.

Raises:

Type Description
ParserExistsError

If the path does not exist.

from_fileobj classmethod
from_fileobj(file: IO, **kwargs) -> Self

Build an object from an open, seekable binary stream.

The position of the stream is restored.

Parameters:

Name Type Description Default
file file object

The stream, open in binary mode.

required
**kwargs Any

The options of the format.

{}

Returns:

Type Description
Self

The object.

from_content classmethod
from_content(content: ContentLike, **kwargs) -> Self

Read an object from bytes, text, or lines.

from_bytes classmethod
from_bytes(content: BinaryContentLike, **kwargs) -> Self

Read an object from binary content.

Compressed content is decompressed first. If the class implements from_fileobj itself, the content is wrapped in an io.BytesIO and read with that method. Otherwise, this method raises, because the default from_fileobj would pass the content back to from_bytes and the fallback would recurse. An override that only forwards to super().from_fileobj should be marked with passthrough_from_fileobj. If such an override is not marked, the loop is still detected when this method is entered again for the same class.

Raises:

Type Description
ParserNotImplementedError

If neither this method nor from_fileobj is implemented.

from_text classmethod
from_text(text: str, **kwargs) -> Self

Read an object from text.

The text is split into lines and passed to from_lines.

from_lines classmethod
from_lines(lines: Iterable[str], **kwargs) -> Self

Read an object from an iterable of lines.

The first line is passed to from_line.

from_line classmethod
from_line(line: str, **kwargs) -> Self

Read an object from a single line.

Raises:

Type Description
ParserNotImplementedError

In the base class, which cannot read a line.

sniff_h5 classmethod
sniff_h5(
    h5file: File, error: bool | Type[Exception] = False
) -> float

Return the confidence that an open HDF5 file is of this format.

A concrete format implements this method.

Parameters:

Name Type Description Default
h5file File

The file, open for reading.

required
error bool or type[Exception]

Whether to raise an error when the content is not of this format. With True, the error is a SnifferContentError, and an exception class is raised instead when one is given.

False

Returns:

Type Description
float

The confidence that the content is of this format.

Raises:

Type Description
NotImplementedError

If the format does not implement it.

from_h5 classmethod
from_h5(h5file: File, **kwargs) -> Self

Build an object from an open HDF5 file.

A concrete format implements this method.

Parameters:

Name Type Description Default
h5file File

The file, open for reading.

required
**kwargs Any

The options of the format.

{}

Returns:

Type Description
Self

The object.

Raises:

Type Description
NotImplementedError

If the format does not implement it.

to_h5
to_h5(h5file: File, **kwargs) -> None

Write the object into an empty HDF5 file open for writing.

A concrete format implements this method.

Parameters:

Name Type Description Default
h5file File

The file, empty and open for writing.

required
**kwargs Any

The options of the writer.

{}

Raises:

Type Description
NotImplementedError

If the format does not implement it.

to_file
to_file(file: H5Like, **kwargs) -> None

Write to a path, a binary stream or an open HDF5 file.

Parameters:

Name Type Description Default
file path-like, h5py.File or file object

Where to write.

required
**kwargs Any

The options of the writer.

{}
to_filename
to_filename(filename: str | PathLike, **kwargs) -> None

Write to the file at a path, replacing it.

A local file is written beside its target, which it then replaces at once. A lazy array that reads the old file, such as a field of an object that was loaded from that same file, therefore reads the old content while the new file is written, and an error while the content is written leaves the target as it was. Other paths are written in place.

Parameters:

Name Type Description Default
filename path - like

The path of the file.

required
**kwargs Any

The options of the writer.

{}
to_bytes
to_bytes(**kwargs) -> bytes

Return the bytes of an HDF5 file that encodes the object.

Parameters:

Name Type Description Default
**kwargs Any

The options of the writer.

{}

Returns:

Type Description
bytes

The content of the file.