Skip to content

Summary

coola.summary

Utilities to build readable summaries for nested data structures.

A summary is a short text that a person reads in a log, a notebook or an error message, to know what a (possibly huge, nested, partly unprintable) object contains.

Properties:

  • Bounded output: a node shows at most max_items children, a text is cut at max_characters, and the expansion stops at max_depth. What is not shown is announced.
  • Bounded work: the cost depends on the size of the output, not on the size of the data.
  • Display depth: max_depth is the number of levels that are expanded. Deeper nodes are shown on one line. It never raises.
  • Total: summarizing never fails because of the data (a __len__ or a property that raises is replaced by a placeholder).
  • Cycle-safe: a container that contains itself is shown as <cycle>.
  • Any depth: there is no RecursionError, the engine uses an explicit stack.
  • Type dispatch: the summarizer is chosen from the type of the data along the Method Resolution Order, so the most specific registered type wins.
  • Registry-extensible: a new type is supported by registering one summarizer.
  • Metadata first: an array, a tensor, a data frame shows its metadata, not its values.
  • Iterators are not consumed: a generator or an iterator is a leaf.
  • Deterministic: the same value gives the same text across calls and processes (a set shows its smallest items in order).
  • Pure: the data is never modified.
  • For humans: the output is meant to be read, not parsed, so its exact format can change.

Not guaranteed: a container that is reachable by several paths is shown once per path, and the time of a user __str__ or __repr__ is not bounded.

coola.summary.BaseMetadataSummarizer

Bases: BaseSummarizer[T]

Define the base class of the summarizers of objects that are described by their metadata (arrays, tensors, data frames, ...).

A subclass implements _describe and, if the type needs an optional library, _check_dependencies. The summary is a leaf: the type followed by the fields, separated by |. If config.show_data is True, it is the repr of the data (cut by the engine at max_characters).

Raises:

Type Description
MissingPackageError

If the optional library of the type is not installed (raised when the summarizer is created).

Example
>>> import numpy as np
>>> from coola.summary import NDArraySummarizer, SummaryConfig
>>> summarizer = NDArraySummarizer()
>>> print(summarizer.summarize(np.ones((2, 3)), SummaryConfig(), compact=False))
<class 'numpy.ndarray'> | shape=(2, 3) | dtype=float64
>>> print(summarizer.summarize(np.ones(2), SummaryConfig(show_data=True), compact=False))
array([1., 1.])

coola.summary.BaseSummarizer

Bases: ABC, Generic[T]

Abstract base class for implementing data summarizers.

A summarizer describes one type: it returns a str for a leaf, or a Node (a header and lazy children) for a container. The engine recurses into the children, so a summarizer does not call the registry.

Notes

The rules of the contract:

  1. summarize is pure and cheap: it does not call the registry, does not recurse, does not modify data and does not iterate the whole data. For a container, it reads len(data) and returns the children lazily. A set is the exception: it returns its smallest max_items items.
  2. compact is True when the data is at the display depth. A leaf may use it. A container ignores it: the engine shows it on one line.
  3. A leaf returns a str, which may have several lines. The engine cuts it at max_characters.
  4. The labels of the children can be any object: the engine writes their str cut at max_characters.
  5. An exception (of summarize, of the iteration of the children, of the str of a label) is handled by the engine, which writes a placeholder. The summarizer does not guard itself.
Example
>>> from coola.summary import DefaultSummarizer, SummaryConfig
>>> summarizer = DefaultSummarizer()
>>> print(summarizer.summarize(1, SummaryConfig(), compact=False))
<class 'int'> 1

coola.summary.BaseSummarizer.equal

equal(other: object) -> bool

Check equality between this summarizer and another object.

Two summarizers are equal if they have the exact same type: the built-in summarizers are stateless. A summarizer with a state should override this method.

Parameters:

Name Type Description Default
other object

The object to compare with this summarizer.

required

Returns:

Type Description
bool

True if the objects are equal, otherwise False.

Example
>>> from coola.summary import DefaultSummarizer, MappingSummarizer
>>> DefaultSummarizer().equal(DefaultSummarizer())
True
>>> DefaultSummarizer().equal(MappingSummarizer())
False

coola.summary.BaseSummarizer.summarize abstractmethod

summarize(
    data: T, config: SummaryConfig, *, compact: bool
) -> str | Node

Describe the data.

Parameters:

Name Type Description Default
data T

The data to describe.

required
config SummaryConfig

The options of the summary.

required
compact bool

True if the data is at the display depth, so it is shown on one line.

required

Returns:

Type Description
str | Node

A str for a leaf, or a Node for a container.

Example
>>> from coola.summary import SequenceSummarizer, SummaryConfig
>>> node = SequenceSummarizer().summarize([1, 2], SummaryConfig(), compact=False)
>>> node.header
"<class 'list'> (length=2)"

coola.summary.DataclassSummarizer

Bases: BaseObjectFieldsSummarizer[Any]

Implement a summarizer for dataclasses.

The children are the fields of the dataclass, labeled by their name. The fields declared with field(repr=False) are not shown, as they are not in the repr: it is the standard way to hide a token or a large buffer.

Example
>>> from dataclasses import dataclass
>>> from coola.summary import DataclassSummarizer, SummaryConfig
>>> @dataclass
... class Point:
...     x: float
...     y: float
>>> node = DataclassSummarizer().summarize(Point(1.0, 2.0), SummaryConfig(), compact=False)
>>> list(node.children)
[('x', 1.0), ('y', 2.0)]
>>> node.total
2
>>> from dataclasses import field
>>> @dataclass
... class User:
...     name: str
...     token: str = field(default="secret", repr=False)
>>> node = DataclassSummarizer().summarize(User("a"), SummaryConfig(), compact=False)
>>> list(node.children)
[('name', 'a')]

coola.summary.DefaultSummarizer

Bases: BaseSummarizer[object]

Implement a default summarizer that returns the str of the data.

The summarizer is a leaf: it shows the type and the str of the data, and only the str when the data is at the display depth. The text is cut so that the type is kept: the line has at most max_characters characters, and the type is only cut if the limit is shorter than the type followed by .... It is registered for object, so it is used for the types that have no other summarizer (numbers, strings, iterators, ...).

Example
>>> from coola.summary import DefaultSummarizer, SummaryConfig
>>> summarizer = DefaultSummarizer()
>>> print(summarizer.summarize(1, SummaryConfig(), compact=False))
<class 'int'> 1
>>> print(summarizer.summarize(1, SummaryConfig(), compact=True))
1

coola.summary.JaxArraySummarizer

Bases: BaseMetadataSummarizer[ndarray]

Implement a summarizer for jax.numpy.ndarray objects.

By default, it displays the metadata (type, shape, dtype) rather than the values.

Raises:

Type Description
MissingPackageError

If JAX is not installed.

Example
>>> import jax.numpy as jnp
>>> from coola.summary import JaxArraySummarizer, SummaryConfig
>>> summarizer = JaxArraySummarizer()
>>> print(summarizer.summarize(jnp.ones((2, 3)), SummaryConfig(), compact=False))  # doctest: +ELLIPSIS
<class '...'> | shape=(2, 3) | dtype=float32

coola.summary.MappingSummarizer

Bases: BaseSummarizer['Mapping[Any, Any]']

Implement a summarizer for mappings (dict, Mapping, MappingProxyType, ...).

The children are the (key, value) pairs, in the order of the mapping. The pairs are taken lazily, so only max_items of them are read.

Example
>>> from coola.summary import MappingSummarizer, SummaryConfig
>>> node = MappingSummarizer().summarize({"a": 1, "b": 2}, SummaryConfig(), compact=False)
>>> node.header
"<class 'dict'> (length=2)"
>>> list(node.children)
[('a', 1), ('b', 2)]
>>> node.total
2

coola.summary.NDArraySummarizer

Bases: BaseMetadataSummarizer[ndarray]

Implement a summarizer for numpy.ndarray objects.

This summarizer generates compact string representations of NumPy arrays. By default, it displays metadata (type, shape, dtype) rather than array values, making it suitable for logging and debugging large arrays. Optionally, it can show the full array representation.

Raises:

Type Description
MissingPackageError

If NumPy is not installed or available.

Example
>>> import numpy as np
>>> from coola.summary import NDArraySummarizer, SummaryConfig

>>> # Default behavior: show metadata only
>>> summarizer = NDArraySummarizer()
>>> print(summarizer.summarize(np.arange(11), SummaryConfig(), compact=False))
<class 'numpy.ndarray'> | shape=(11,) | dtype=int64

>>> # Works with arrays of any shape and dtype
>>> print(summarizer.summarize(np.ones((2, 3, 4)), SummaryConfig(), compact=False))
<class 'numpy.ndarray'> | shape=(2, 3, 4) | dtype=float64

>>> # Show full array data
>>> config = SummaryConfig(show_data=True)
>>> print(summarizer.summarize(np.arange(11), config, compact=False))
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

coola.summary.Node dataclass

Describe a container for the engine.

Parameters:

Name Type Description Default
header str

The first line of the node, for example "<class 'list'> (length=3)".

required
children Iterable[tuple[Any, Any]]

The (label, child) pairs, in display order. It should be lazy (a generator, enumerate(data), data.items()): the engine takes at most max_items of them.

required
total int

The number of children, used to announce ... (+N more) when some of them are not shown.

required
Example
>>> from coola.summary import Node
>>> node = Node("<class 'list'> (length=2)", enumerate(["a", "b"]), 2)
>>> node.header
"<class 'list'> (length=2)"
>>> list(node.children)
[(0, 'a'), (1, 'b')]
>>> node.total
2

coola.summary.PandasDataFrameSummarizer

Bases: BaseMetadataSummarizer[DataFrame]

Implement a summarizer for pandas.DataFrame objects.

By default, it displays the metadata (type, shape, columns with their dtype) rather than the values, which makes it suitable for logging large data frames. At most max_items columns are listed.

Raises:

Type Description
MissingPackageError

If pandas is not installed.

Example
>>> import pandas as pd
>>> from coola.summary import PandasDataFrameSummarizer, SummaryConfig
>>> summarizer = PandasDataFrameSummarizer()
>>> frame = pd.DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]})
>>> print(summarizer.summarize(frame, SummaryConfig(), compact=False))
<class 'pandas.DataFrame'> | shape=(3, 2) | columns=a: int64, b: float64

coola.summary.PandasSeriesSummarizer

Bases: BaseMetadataSummarizer[Series]

Implement a summarizer for pandas.Series objects.

By default, it displays the metadata (type, shape, dtype, name) rather than the values.

Raises:

Type Description
MissingPackageError

If pandas is not installed.

Example
>>> import pandas as pd
>>> from coola.summary import PandasSeriesSummarizer, SummaryConfig
>>> summarizer = PandasSeriesSummarizer()
>>> print(summarizer.summarize(pd.Series([1, 2, 3], name="a"), SummaryConfig(), compact=False))
<class 'pandas.Series'> | shape=(3,) | dtype=int64 | name='a'

coola.summary.PolarsDataFrameSummarizer

Bases: BaseMetadataSummarizer[DataFrame]

Implement a summarizer for polars.DataFrame objects.

By default, it displays the metadata (type, shape, columns with their dtype) rather than the values. At most max_items columns are listed.

Raises:

Type Description
MissingPackageError

If polars is not installed.

Example
>>> import polars as pl
>>> from coola.summary import PolarsDataFrameSummarizer, SummaryConfig
>>> summarizer = PolarsDataFrameSummarizer()
>>> frame = pl.DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]})
>>> print(summarizer.summarize(frame, SummaryConfig(), compact=False))  # doctest: +ELLIPSIS
<class '...'> | shape=(3, 2) | columns=a: Int64, b: Float64

coola.summary.PolarsLazyFrameSummarizer

Bases: BaseMetadataSummarizer[LazyFrame]

Implement a summarizer for polars.LazyFrame objects.

The lazy frame is not collected: only its schema is read, so the number of rows is not shown. At most max_items columns are listed.

Raises:

Type Description
MissingPackageError

If polars is not installed.

Example
>>> import polars as pl
>>> from coola.summary import PolarsLazyFrameSummarizer, SummaryConfig
>>> summarizer = PolarsLazyFrameSummarizer()
>>> frame = pl.LazyFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]})
>>> print(summarizer.summarize(frame, SummaryConfig(), compact=False))  # doctest: +ELLIPSIS
<class '...'> | columns=a: Int64, b: Float64

coola.summary.PolarsSeriesSummarizer

Bases: BaseMetadataSummarizer[Series]

Implement a summarizer for polars.Series objects.

By default, it displays the metadata (type, shape, dtype, name) rather than the values.

Raises:

Type Description
MissingPackageError

If polars is not installed.

Example
>>> import polars as pl
>>> from coola.summary import PolarsSeriesSummarizer, SummaryConfig
>>> summarizer = PolarsSeriesSummarizer()
>>> print(summarizer.summarize(pl.Series("a", [1, 2, 3]), SummaryConfig(), compact=False))  # doctest: +ELLIPSIS
<class '...'> | shape=(3,) | dtype=Int64 | name='a'

coola.summary.PyarrowArraySummarizer

Bases: BaseMetadataSummarizer['pa.Array | pa.ChunkedArray']

Implement a summarizer for pyarrow.Array and pyarrow.ChunkedArray objects.

By default, it displays the metadata (type, length, arrow type) rather than the values.

Raises:

Type Description
MissingPackageError

If pyarrow is not installed.

Example
>>> import pyarrow as pa
>>> from coola.summary import PyarrowArraySummarizer, SummaryConfig
>>> summarizer = PyarrowArraySummarizer()
>>> print(summarizer.summarize(pa.array([1, 2, 3]), SummaryConfig(), compact=False))  # doctest: +ELLIPSIS
<class '...'> | length=3 | type=int64

coola.summary.PyarrowTableSummarizer

Bases: BaseMetadataSummarizer['pa.Table | pa.RecordBatch']

Implement a summarizer for pyarrow.Table and pyarrow.RecordBatch objects.

By default, it displays the metadata (type, shape, columns with their arrow type) rather than the values. At most max_items columns are listed.

Raises:

Type Description
MissingPackageError

If pyarrow is not installed.

Example
>>> import pyarrow as pa
>>> from coola.summary import PyarrowTableSummarizer, SummaryConfig
>>> summarizer = PyarrowTableSummarizer()
>>> table = pa.table({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]})
>>> print(summarizer.summarize(table, SummaryConfig(), compact=False))  # doctest: +ELLIPSIS
<class '...'> | shape=(3, 2) | columns=a: int64, b: double

coola.summary.PydanticModelSummarizer

Bases: BaseObjectFieldsSummarizer['pydantic.BaseModel']

Summarizer for pydantic.BaseModel instances.

The children are the fields and the extra values of the model, labeled by their name. The fields annotated as a secret type (SecretStr, SecretBytes) are not shown, as in str_pydantic_model.

Example
>>> from pydantic import BaseModel, SecretStr
>>> from coola.summary import SummaryConfig
>>> from coola.summary.pydantic import PydanticModelSummarizer
>>> class User(BaseModel):
...     name: str
...     password: SecretStr
...
>>> node = PydanticModelSummarizer().summarize(
...     User(name="a", password="b"), SummaryConfig(), compact=False
... )
>>> list(node.children)
[('name', 'a')]

coola.summary.SequenceSummarizer

Bases: BaseSummarizer['Sequence[Any]']

Implement a summarizer for sequences (list, tuple, deque, ...).

The children are the items, labeled by their position, or by their field name for a named tuple. The items are taken lazily, so only max_items of them are read.

Example
>>> from coola.summary import SequenceSummarizer, SummaryConfig
>>> node = SequenceSummarizer().summarize([1, 2, 3], SummaryConfig(), compact=False)
>>> node.header
"<class 'list'> (length=3)"
>>> list(node.children)
[(0, 1), (1, 2), (2, 3)]
>>> node.total
3

coola.summary.SetSummarizer

Bases: BaseSummarizer['AbstractSet[Any]']

Implement a summarizer for sets (set, frozenset).

The children are the max_items smallest items, in order, so the summary does not depend on the iteration order of the set (and on PYTHONHASHSEED). The items that cannot be compared (for example an int and a str) are shown in iteration order.

Example
>>> from coola.summary import SetSummarizer, SummaryConfig
>>> node = SetSummarizer().summarize({3, 1, 2}, SummaryConfig(max_items=2), compact=False)
>>> node.header
"<class 'set'> (length=3)"
>>> list(node.children)
[(0, 1), (1, 2)]
>>> node.total
3

coola.summary.Summarizer

Bases: Protocol[T_contra]

Structural interface of a type-specific summarizer.

Any object with a compatible summarize method can be registered without subclassing BaseSummarizer, which remains available as a convenience base class.

coola.summary.Summarizer.summarize

summarize(
    data: T_contra, config: SummaryConfig, *, compact: bool
) -> str | Node

Summarize the data.

Parameters:

Name Type Description Default
data T_contra

The data to summarize.

required
config SummaryConfig

The options of the summary.

required
compact bool

If True, the node is not expanded, so a summary on one line is enough.

required

Returns:

Type Description
str | Node

A str for a leaf, or a Node (a header and lazy

str | Node

children) for a container.

coola.summary.SummarizerRegistry

Bases: TypeRegistry[Summarizer[Any]]

Registry that manages and dispatches summarizers based on data type.

This registry maintains a mapping from Python types to summarizer instances and uses the Method Resolution Order (MRO) for type lookup. When summarizing data, it automatically selects the most specific registered summarizer for the data's type, falling back to parent types or a default summarizer if needed.

Type lookups are cached internally for performance. The cache is cleared automatically whenever the registry is modified (e.g. via register or register_many).

Parameters:

Name Type Description Default
initial_state dict[type, T] | None

Optional initial mapping of types to summarizers. If provided, the state is copied to prevent external mutations.

None
Example

Basic usage with a sequence summarizer:

>>> from coola.summary import SummarizerRegistry, SequenceSummarizer, DefaultSummarizer
>>> registry = SummarizerRegistry({object: DefaultSummarizer(), list: SequenceSummarizer()})
>>> registry
SummarizerRegistry(
  (<class 'object'>): DefaultSummarizer()
  (<class 'list'>): SequenceSummarizer()
)
>>> print(registry.summarize([1, 2, 3]))
<class 'list'> (length=3)
  (0): 1
  (1): 2
  (2): 3

Registering custom summarizers:

>>> from coola.summary import SummarizerRegistry, SequenceSummarizer
>>> registry = SummarizerRegistry({object: DefaultSummarizer()})
>>> registry.register(tuple, SequenceSummarizer())
>>> print(registry.summarize((1, 2, 3)))
<class 'tuple'> (length=3)
  (0): 1
  (1): 2
  (2): 3

Working with nested structures:

>>> from coola.summary import get_default_registry
>>> registry = get_default_registry()
>>> print(registry.summarize({"a": [1, 2], "b": [3, 4]}))
<class 'dict'> (length=2)
  (a): [1, 2]
  (b): [3, 4]

coola.summary.SummarizerRegistry.find_summarizer

find_summarizer(data_type: type) -> Summarizer[Any]

Type-specific alias for find: find the appropriate summarizer for a given type.

See TypeRegistry.resolve for the full behavior description (MRO resolution, caching, and the KeyError on no match).

Parameters:

Name Type Description Default
data_type type

The Python type to find a summarizer for.

required

Returns:

Type Description
Summarizer[Any]

The most specific registered summarizer for this type, resolved

Summarizer[Any]

via MRO, or the default summarizer if no match is found.

Example
>>> from coola.summary import get_default_registry
>>> registry = get_default_registry()
>>> summarizer = registry.find_summarizer(list)
>>> summarizer
SequenceSummarizer()

coola.summary.SummarizerRegistry.has_summarizer

has_summarizer(data_type: type) -> bool

Type-specific alias for has: check if a summarizer is explicitly registered for the given type.

See Registry.has for the full behavior description.

Parameters:

Name Type Description Default
data_type type

The type to check.

required

Returns:

Type Description
bool

True if a summarizer is explicitly registered for this type, False otherwise.

Example
>>> from coola.summary import SummarizerRegistry, SequenceSummarizer
>>> registry = SummarizerRegistry({list: SequenceSummarizer()})
>>> registry.has_summarizer(list)
True
>>> registry.has_summarizer(tuple)
False

coola.summary.SummarizerRegistry.summarize

summarize(
    data: object, config: SummaryConfig | None = None
) -> str

Generate a formatted string summary of the provided data.

The summary is built by the engine (see coola.summary.engine), which expands the nodes with the summarizer of their type, up to config.max_depth levels.

Parameters:

Name Type Description Default
data object

The data to summarize. Can be any Python object, though behavior depends on the registered summarizers.

required
config SummaryConfig | None

The options of the summary. If None, the default options are used.

None

Returns:

Type Description
str

A formatted string representation of the data. The exact format depends on the registered summarizers, but it includes type information, size metadata, and indented content for nested structures.

Raises:

Type Description
KeyError

If no summarizer is registered for a type of the data, and not even for object.

Example
>>> from coola.summary import SummaryConfig, get_default_registry
>>> registry = get_default_registry()
>>> print(registry.summarize(1))
<class 'int'> 1
>>> print(registry.summarize(["abc", "def"]))
<class 'list'> (length=2)
  (0): abc
  (1): def
>>> print(registry.summarize([[0, 1, 2], {"key1": "abc"}]))
<class 'list'> (length=2)
  (0): [0, 1, 2]
  (1): {'key1': 'abc'}
>>> print(registry.summarize([[0, 1, 2], {"key1": "abc"}], SummaryConfig(max_depth=2)))
<class 'list'> (length=2)
  (0): <class 'list'> (length=3)
    (0): 0
    (1): 1
    (2): 2
  (1): <class 'dict'> (length=1)
    (key1): abc

coola.summary.SummaryConfig dataclass

Define the options of a summary.

The config is validated when it is created. It is immutable and hashable, so it can be shared by threads and calls.

Parameters:

Name Type Description Default
max_depth int

A display depth, not a limit that raises: the number of levels that are expanded. The nodes below this depth are shown on one line. Must be a non-negative int.

1
max_items int | None

The maximum number of children (items, fields, columns) shown for a node. The other ones are announced with ... (+N more). None shows all of them. Must be a non-negative int or None.

5
max_characters int | None

The maximum number of characters of a text, including the ... that marks a cut. A leaf keeps its type and cuts the value, unless the limit is shorter than the type. None does not cut the texts. Must be a non-negative int or None.

1000
show_data bool

If True, the summarizers of arrays, tensors and frames show a bounded repr of the data instead of its metadata.

False

Raises:

Type Description
TypeError

If max_depth, max_items or max_characters is not an int (a bool is rejected), or if show_data is not a bool.

ValueError

If max_depth, max_items or max_characters is negative.

Example
>>> from coola.summary import SummaryConfig
>>> SummaryConfig()
SummaryConfig(max_depth=1, max_items=5, max_characters=1000, show_data=False)
>>> SummaryConfig(max_depth=3, max_items=None)
SummaryConfig(max_depth=3, max_items=None, max_characters=1000, show_data=False)

coola.summary.TensorSummarizer

Bases: BaseMetadataSummarizer[Tensor]

Implement a summarizer for torch.Tensor objects.

This summarizer generates compact string representations of PyTorch tensors. By default, it displays metadata (type, shape, dtype, device, requires_grad) rather than tensor values, making it suitable for logging and debugging large tensors. Optionally, it can show the full tensor representation.

Raises:

Type Description
MissingPackageError

If PyTorch is not installed or available.

Example
>>> import torch
>>> from coola.summary import TensorSummarizer, SummaryConfig

>>> # Default behavior: show metadata only
>>> summarizer = TensorSummarizer()
>>> print(summarizer.summarize(torch.arange(11), SummaryConfig(), compact=False))  # doctest: +ELLIPSIS
<class 'torch.Tensor'> | shape=torch.Size([11]) | dtype=torch.int64 | device=cpu | requires_grad=False

>>> # Works with tensors of any shape and dtype
>>> print(summarizer.summarize(torch.ones(2, 3, 4), SummaryConfig(), compact=False))  # doctest: +ELLIPSIS
<class 'torch.Tensor'> | shape=torch.Size([2, 3, 4]) | dtype=torch.float32 | device=cpu | requires_grad=False

>>> # Show full tensor data
>>> config = SummaryConfig(show_data=True)
>>> print(summarizer.summarize(torch.arange(11), config, compact=False))  # doctest: +ELLIPSIS
tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

coola.summary.XarrayDataArraySummarizer

Bases: BaseMetadataSummarizer[DataArray]

Implement a summarizer for xarray.DataArray objects.

By default, it displays the metadata (type, dimensions, shape, dtype, name) rather than the values.

Raises:

Type Description
MissingPackageError

If xarray is not installed.

Example
>>> import numpy as np
>>> import xarray as xr
>>> from coola.summary import XarrayDataArraySummarizer, SummaryConfig
>>> summarizer = XarrayDataArraySummarizer()
>>> array = xr.DataArray(np.ones((2, 3)), dims=("x", "y"), name="a")
>>> print(summarizer.summarize(array, SummaryConfig(), compact=False))  # doctest: +ELLIPSIS
<class '...'> | dims=('x', 'y') | shape=(2, 3) | dtype=float64 | name='a'

coola.summary.XarrayDatasetSummarizer

Bases: BaseMetadataSummarizer[Dataset]

Implement a summarizer for xarray.Dataset objects.

By default, it displays the metadata (type, dimensions with their size, data variables with their dtype) rather than the values. At most 10 data variables are listed.

Raises:

Type Description
MissingPackageError

If xarray is not installed.

Example
>>> import numpy as np
>>> import xarray as xr
>>> from coola.summary import XarrayDatasetSummarizer, SummaryConfig
>>> summarizer = XarrayDatasetSummarizer()
>>> dataset = xr.Dataset({"a": (("x",), np.ones(3)), "b": (("x",), np.zeros(3))})
>>> print(summarizer.summarize(dataset, SummaryConfig(), compact=False))  # doctest: +ELLIPSIS
<class '...'> | dims={'x': 3} | data_vars=a: float64, b: float64

coola.summary.XarrayVariableSummarizer

Bases: BaseMetadataSummarizer[Variable]

Implement a summarizer for xarray.Variable objects.

By default, it displays the metadata (type, dimensions, shape, dtype) rather than the values.

Raises:

Type Description
MissingPackageError

If xarray is not installed.

Example
>>> import numpy as np
>>> import xarray as xr
>>> from coola.summary import XarrayVariableSummarizer, SummaryConfig
>>> summarizer = XarrayVariableSummarizer()
>>> variable = xr.Variable(("x", "y"), np.ones((2, 3)))
>>> print(summarizer.summarize(variable, SummaryConfig(), compact=False))  # doctest: +ELLIPSIS
<class '...'> | dims=('x', 'y') | shape=(2, 3) | dtype=float64

coola.summary.format_fields

format_fields(
    fields: Iterable[tuple[Any, Any]],
    max_fields: int | None,
) -> str

Format (name, type) pairs as name: type, with at most max_fields of them.

Parameters:

Name Type Description Default
fields Iterable[tuple[Any, Any]]

The (name, type) pairs, for example the columns of a data frame and their types.

required
max_fields int | None

The maximum number of pairs to show. The other ones are replaced by ... (+N more). None shows all of them.

required

Returns:

Type Description
str

The formatted pairs, separated by a comma.

Example
>>> from coola.summary import format_fields
>>> format_fields([("a", "int64"), ("b", "float64")], 5)
'a: int64, b: float64'
>>> format_fields([("a", "int64"), ("b", "float64"), ("c", "object")], 1)
'a: int64, ... (+2 more)'

coola.summary.get_default_registry

get_default_registry() -> SummarizerRegistry

Get or create the default global registry with common Python types.

Returns a singleton registry instance that is pre-configured with summarizers for Python's built-in types including sequences (list, tuple), mappings (dict), sets, and scalar types (int, float, str, bool).

This function uses a singleton pattern to ensure the same registry instance is returned on subsequent calls, which is efficient and maintains consistency across an application.

Returns:

Type Description
SummarizerRegistry

A singleton SummarizerRegistry configured for common built-in

SummarizerRegistry

scalar and container types.

Notes

The singleton pattern means modifications to the returned registry affect all future calls to this function. If you need an isolated registry, create a new SummarizerRegistry instance directly.

Example
>>> from coola.summary import get_default_registry
>>> registry = get_default_registry()
>>> # Registry is ready to use with common Python types
>>> print(registry.summarize([1, 2, 3]))
<class 'list'> (length=3)
  (0): 1
  (1): 2
  (2): 3
>>> print(registry.summarize({"a": 1, "b": 2}))
<class 'dict'> (length=2)
  (a): 1
  (b): 2

coola.summary.register_summarizers

register_summarizers(
    mapping: Mapping[type, Summarizer[Any]],
    *,
    exist_ok: bool = False,
) -> None

Register custom summarizers to the default global registry.

This function extends the singleton registry returned by get_default_registry.

Parameters:

Name Type Description Default
mapping Mapping[type, Summarizer[Any]]

Mapping of Python types to summarizer instances.

required
exist_ok bool

If False, raise an error when a type is already registered.

False
Example
>>> from coola.summary import register_summarizers, BaseSummarizer, SummaryConfig
>>> class MyType:
...     def __init__(self, value):
...         self.value = value
...
>>> class MySummarizer(BaseSummarizer[MyType]):
...     def summarize(self, data: MyType, config: SummaryConfig, *, compact: bool) -> str:
...         return f"<MyType> value={data.value}"
...
>>> register_summarizers({MyType: MySummarizer()})

coola.summary.summarize

summarize(
    data: object,
    *,
    max_depth: int = 1,
    max_items: int | None = 5,
    max_characters: int | None = 1000,
    show_data: bool = False,
    registry: SummarizerRegistry | None = None,
) -> str

Create a summary string representation of nested data.

The options must be passed by keyword.

Parameters:

Name Type Description Default
data object

Input data to summarize.

required
max_depth int

A display depth, not a limit that raises: the number of levels that are expanded. The structures below this depth are shown on one line (unlike the max_depth of objects_are_equal, which raises an error for a deeper structure). Must be non-negative. Default is 1, which expands only the top level of nested structures.

1
max_items int | None

The maximum number of children (items, fields, columns) shown for a node. The other ones are announced with ... (+N more). None shows all of them.

5
max_characters int | None

The maximum number of characters of a text, including the ... that marks a cut. A leaf keeps its type and cuts the value, unless the limit is shorter than the type. None does not cut the texts.

1000
show_data bool

If True, the arrays, tensors and frames show a bounded repr of their values instead of their metadata.

False
registry SummarizerRegistry | None

Registry to resolve summarizers for nested data. If None, the default registry is used.

None

Returns:

Type Description
str

A formatted string summary of data.

Raises:

Type Description
TypeError

If max_depth, max_items or max_characters is not an int (a bool is rejected), or if show_data is not a bool.

ValueError

If max_depth, max_items or max_characters is negative.

Example
>>> from coola.summary import summarize
>>> print(summarize({"a": 1, "b": "abc"}))
<class 'dict'> (length=2)
  (a): 1
  (b): abc
>>> print(summarize(list(range(10)), max_items=3))
<class 'list'> (length=10)
  (0): 0
  (1): 1
  (2): 2
  ... (+7 more)