explorica.reports.core

explorica.reports.core.block

Block module of Explorica Reports

This module provides the Block class, a core building block for constructing analytical reports in Explorica. It allows managing metrics and visualizations within a report block and rendering them to HTML or PDF formats.

Classes

Block(block_config=None)

A container for a report block in Explorica.

BlockConfig

Dataclass for storing configuration of a report block, including title, description, metrics, and visualizations.

Notes

  • Block wraps a BlockConfig instance and normalizes all visualizations into VisualizationResult objects for consistent rendering.

  • HTML and PDF rendering methods are thin wrappers around the renderers, forwarding all parameters for flexibility.

Examples

>>> import matplotlib.pyplot as plt
>>> import plotly.graph_objects as go
>>> from explorica.reports.core import Block, BlockConfig
>>>
>>>
>>> # Simple usage
>>> # Create a matplotlib figure
>>> fig, ax = plt.subplots()
>>> # Create a plotly figure
>>> figly = go.Figure(data=go.Bar(y=[2, 3, 1]))
>>> # Initialize BlockConfig
>>> block_cfg = BlockConfig(
...     title="Example Block",
...     description="A minimal example of Block usage.",
...     metrics=[{"name": "Mean", "value": 5.0}],
...     visualizations=[fig, figly]
... )
>>> # Initialize Block
>>> block = Block(block_cfg)
>>> # Usage of management methods
>>> # Add a new metric
>>> block.add_metric("Std", 1.2, description="Standard deviation")
>>> # Insert a metric at index 0
>>> block.insert_metric(0, "Min", 2.0)
>>> # Add a new visualization
>>> fig2, ax2 = plt.subplots()
>>> block.add_visualization(fig2)
>>> # Insert a visualization at index 1
>>> fig3 = go.Figure(data=go.Scatter(y=[1, 4, 9]))
>>> block.insert_visualization(fig3, 1)
>>> # Render to HTML
>>> html_output = block.render_html(path=None)
>>> print(type(html_output))
<class 'str'>
>>> # Render to PDF
>>> pdf_bytes = block.render_pdf(path=None)
>>> print(type(pdf_bytes))
<class 'bytes'>
>>> # Close all mpl figure after usage
>>> plt.close('all')
class explorica.reports.core.block.Block(block_config=None)[source]

Bases: object

A container for a report block in Explorica.

This class wraps a BlockConfig dataclass and provides utilities for rendering the block into HTML or PDF. During initialization, all figures in block_config.visualizations are normalized into VisualizationResult objects for uniform downstream processing.

Parameters:
block_configdict or BlockConfig, optional

Configuration for the block.

  • If dict -> converted to BlockConfig.

  • If BlockConfig -> used as-is.

  • If None -> a new empty BlockConfig is created.

Attributes:
block_configBlockConfig

The configuration of the block including title, description, metrics, and visualizations (normalized to VisualizationResult).

typename

Return the class name.

empty

Check whether the block contains any content.

Methods

add_visualization(visualization)

Add a visualization to the block.

insert_visualization(visualization, index)

Insert a visualization into the block at a given position.

remove_visualization(index)

Remove a visualization from the block by index.

clear_visualizations()

Remove all visualizations from the block.

add_metric(name, value, description = None)

Add a scalar metric to the block.

insert_metric(index, name, value, description = None)

Insert a scalar metric into the block at a given position.

remove_metric(index)

Remove a metric from the block at a given index.

add_table(table, title = None, description = None)

Add a table to the block.

insert_table(index, table, title = None, description = None)

Insert a table into the block at a given position.

remove_table(index)

Remove and return a table from the block by index.

render_pdf(path = None, font = “DejaVuSans”, doc_template_kws = None, **kwargs)

Render the block to PDF format.

render_html(path=None,font=(“Arial”, “DejaVu Serif”, “DejaVu Sans”, “sans-serif”),

**kwargs)

Render the block to HTML format.

Notes

  • During initialization, all figures in block_config.visualizations are normalized into VisualizationResult objects via normalize_visualization.

  • All tables in block_config.tables are normalized into TableResult objects via normalize_table.

  • This ensures consistent handling for rendering in HTML or PDF and standardized table representation.

  • block_config.visualizations and block_config.tables can be empty or None; in that case, they are initialized as empty lists.

Examples

>>> # Simple usage
>>> from explorica.reports import Block, BlockConfig
>>> import matplotlib.pyplot as plt
>>> import plotly.graph_objects as go
>>>
>>>
>>> # Create a matplotlib figure
>>> fig, ax = plt.subplots()
>>> # Create a plotly figure
>>> figly = go.Figure(data=go.Bar(y=[2, 3, 1]))
>>> # Initialize BlockConfig
>>> block_cfg = BlockConfig(
...     title="Example Block",
...     description="A minimal example of Block usage.",
...     metrics=[{"name": "Mean", "value": 5.0}],
...     visualizations=[fig, figly]
... )
>>> # Initialize Block
>>> block = Block(block_cfg)
>>> # Usage of management methods
>>> # Add a new metric
>>> block.add_metric("Std", 1.2, description="Standard deviation")
>>> # Insert a metric at index 0
>>> block.insert_metric(0, "Min", 2.0)
>>> # Add a new visualization
>>> fig2, ax2 = plt.subplots()
>>> block.add_visualization(fig2)
>>> # Insert a visualization at index 1
>>> fig3 = go.Figure(data=go.Scatter(y=[1, 4, 9]))
>>> block.insert_visualization(fig3, 1)
>>> # Render to HTML
>>> html_output = block.render_html(path=None)
>>> print(type(html_output))
<class 'str'>
>>> # Render to PDF
>>> pdf_bytes = block.render_pdf(path=None)
>>> print(type(pdf_bytes))
<class 'bytes'>
>>> # Close all mpl figure after usage
>>> plt.close('all')
add_metric(name: Hashable, value: Hashable | Sequence[Hashable], description: Hashable = None)[source]

Add a scalar metric to the block.

Metrics represent key numeric indicators that are rendered alongside visualizations in reports.

Parameters:
nameHashable

Metric name. Must be hashable and renderable as text (e.g. str, int, Enum).

valueNumber

Metric value. Can be any hashable scalar or sequence of hashable scalars. Non-hashable types are not supported.

descriptionHashable, optional

Optional metric description. Must be hashable and renderable as text if provided.

Raises:
TypeError

If name, description or value are not hashable.

Notes

  • Metrics are stored internally as dictionaries with keys name, value and description.

Examples

>>> from explorica.reports.core import Block, BlockConfig
>>> block = Block(BlockConfig(title="My Block"))
>>> block.add_metric("mean", 5.2)
>>> block.add_metric("std", 1.3, description="Standard deviation")
>>> block.block_config.metrics
[{'name': 'mean', ...}, {'name': 'std', ...}]
add_table(table: Sequence[Any] | Mapping[str, Sequence], title: str = None, description: str = None)[source]

Add a table to the block.

The provided table data is normalized into a TableResult instance during insertion. Supported inputs include 1D/2D sequences and mapping-like objects (e.g. dictionaries), which are internally converted to a pandas DataFrame.

Parameters:
tableSequence[Any] or Mapping[str, Sequence]

Tabular data to add. Can be a 1D or 2D sequence, or a mapping of sequences.

titlestr, optional

Optional table title. If table is already a TableResult, this value will overwrite its existing title. Used during rendering.

descriptionstr, optional

Optional table description. If table is already a TableResult, this value will overwrite its existing description. Used during rendering.

Notes

  • The input data is normalized and wrapped into a TableResult.

  • MultiIndex or multi-column DataFrames are not supported and may raise an error during normalization.

Examples

>>> from explorica.reports.core import Block, BlockConfig
>>> # Simple usage
>>> block = Block(BlockConfig(title='My Block'))
>>> block.add_table(
...     {"mean": [1.2], "std": [0.3]},
...     title="Summary statistics"
... )
>>> block.block_config.tables
[TableResult(...)]
add_visualization(visualization: Figure | Figure | VisualizationResult)[source]

Add a visualization to the block.

The visualization is normalized into a VisualizationResult object before being appended to the block’s list of visualizations.

Parameters:
visualizationmpl.figure.Figure, plotly.go.Figure, or VisualizationResult

The figure or visualization object to add to the block.

Notes

  • normalize_visualization is applied automatically to ensure a uniform internal representation.

  • This method does not render the visualization; it only stores it for future rendering via render_html or render_pdf.

Examples

>>> import matplotlib.pyplot as plt
>>> from explorica.reports.core import Block
>>> fig, ax = plt.subplots()
>>> block = Block()
>>> block.add_visualization(fig)
>>> # Close all mpl figure after usage
>>> plt.close('all')
clear_visualizations()[source]

Remove all visualizations from the block.

This method clears the list of visualizations associated with the block.

Examples

>>> import matplotlib.pyplot as plt
>>> from explorica.reports import Block, BlockConfig
>>> fig, ax = plt.subplots()
>>> block = Block(BlockConfig(visualizations=[fig]))
>>> block.clear_visualizations()
>>> block.block_config.visualizations
[]
>>> # Close all mpl figure after usage
>>> plt.close('all')
close_figures()[source]

Close all Matplotlib figures associated with this block.

Iterates over all visualizations registered in the block configuration and closes underlying Matplotlib Figure objects, if present. This method is intended to free graphical resources and prevent accumulation of open figures in long-running processes or batch report generation.

See also

matplotlib.pyplot.close

Close a Matplotlib figure and release its resources.

Notes

  • Only visualizations backed by Matplotlib figures are affected.

  • Visualizations using other backends are ignored.

  • Calling this method does not remove visualizations from the block; it only closes their associated figures.

Examples

>>> from explorica.reports.core import Block, BlockConfig
>>> block = Block(BlockConfig())
>>> # ... generate visualizations and render block ...
>>> block.close_figures()
property empty

Check whether the block contains any content.

Returns True if the block contains no metrics, visualizations, or tables, otherwise returns False.

This is a convenient pseudo-attribute to quickly determine whether a Block is empty without inspecting individual collections.

Examples

>>> import pandas as pd
>>> from explorica.reports.core import Block, BlockConfig
>>> # Simple usage
>>> block = Block(BlockConfig(title="Empty block"))
>>> block.empty
True
>>> from explorica.types import TableResult
>>> block.add_table(TableResult(table=pd.DataFrame()))
>>> block.empty
False
insert_metric(index: int, name: Hashable, value: Hashable | Sequence[Hashable], description: Hashable = None)[source]

Insert a scalar metric into the block at a given position.

This method behaves like add_metric(), but allows explicit control over the insertion index. Metric validation rules are identical to those of add_metric().

Parameters:
indexint

Position at which the metric should be inserted. Follows standard Python list.insert semantics.

nameHashable

Metric name. Must be hashable and renderable as text (e.g. str, int, Enum).

valueHashable or Sequence[Hashable]

Metric value. Can be any hashable scalar or sequence of hashable scalars.

descriptionHashable, optional

Optional metric description. Must be hashable and renderable as text if provided.

Raises:
TypeError

If name, description or value are not hashable.

Notes

  • This method follows standard Python list.insert behavior for index handling.

  • Negative indices are supported and follow standard Python semantics.

  • Metric validation is performed via the internal _validate_metric() helper.

Examples

>>> from explorica.reports.core import Block, BlockConfig
>>> block = Block(BlockConfig(title="My Block"))
>>> block.insert_metric(0, "mean", 5.2)
>>> block.insert_metric(0, "std", 1.3, description="Standard deviation")
>>> block.block_config.metrics
[{'name': 'std', ...}, {'name': 'mean', ...}]
insert_table(index: int, table: Sequence[Any] | Mapping[str, Sequence], title: str = None, description: str = None)[source]

Insert a table into the block at a given position.

This method behaves like add_table(), but allows explicit control over the insertion index. Index handling follows standard Python list.insert semantics.

Parameters:
indexint

Position at which the table should be inserted. Supports negative indices.

tableSequence[Any] or Mapping[str, Sequence]

Tabular data to insert. Can be a 1D or 2D sequence, or a mapping of sequences.

titlestr, optional

Optional table title. If table is already a TableResult, this value will overwrite its existing title. Used during rendering.

descriptionstr, optional

Optional table description. If table is already a TableResult, this value will overwrite its existing description. Used during rendering.

Notes

  • The table is normalized into a TableResult before insertion.

  • Negative indices follow standard Python list behavior.

Examples

>>> # Simple usage
>>> from explorica.reports.core import Block, BlockConfig
>>> block = Block(BlockConfig(title="My Block"))
>>> block.insert_table(
...     0,
...     [[1, 2], [3, 4]],
...     title="Table 1"
... )
>>> block.insert_table(
...     0,
...     [[1, 2], [3, 4]],
...     title="Table 2"
... )
>>> block.block_config.tables
[TableResult(..., title='Table 2', ...), TableResult(..., title='Table 1', ...)]
insert_visualization(visualization: Figure | Figure | VisualizationResult, index: int)[source]

Insert a visualization into the block at a given position.

The visualization is normalized into a VisualizationResult object before being inserted into the block’s list of visualizations.

Parameters:
visualizationmpl.figure.Figure, plotly.go.Figure or VisualizationResult

The figure or visualization object to insert.

indexint

Position at which the visualization is inserted. Uses standard Python list insertion semantics.

Notes

  • normalize_visualization is applied automatically to ensure a uniform internal representation.

Examples

>>> import matplotlib.pyplot as plt
>>> from explorica.reports.core import Block
>>> fig, ax = plt.subplots()
>>> block = Block()
>>> block.insert_visualization(fig, index=0)
>>> # Close all mpl figure after usage
>>> plt.close('all')
remove_metric(index: int) dict[source]

Remove a metric from the block at a given index.

This method updates the internal BlockConfig by deleting the metric at the specified position. Supports negative indexing (like Python lists).

Parameters:
indexint

Position of the metric to remove. Follows standard Python list indexing semantics, including support for negative indices.

Returns:
dict

The removed metric, containing keys name, value and description.

Raises:
IndexError

If no metric exists at the given index.

Notes

  • This is a direct wrapper around Python’s list pop method for the internal metrics list.

  • The returned metric is the exact dictionary stored internally.

Examples

>>> from explorica.reports.core import Block, BlockConfig
>>> block = Block(BlockConfig(metrics=[
...     {'name': 'mean', 'value': 5.0, 'description': None},
...     {'name': 'median', 'value': 5.2, 'description': 'Simple desc'},
... ]))
>>> removed = block.remove_metric(0)
>>> print(removed)
{'name': 'mean', 'value': 5.0, 'description': None}
remove_table(index: int) TableResult[source]

Remove and return a table from the block by index.

This method updates the internal BlockConfig by deleting the table at the specified position. Supports negative indexing (like Python lists).

Parameters:
indexint

Position of the table to remove. Supports negative indexing.

Returns:
TableResult

The removed table.

Raises:
IndexError

If no table exists at the given index.

Examples

>>> import pandas as pd
>>> from explorica.reports.core import Block, BlockConfig
>>> # Simple usage
>>> df = pd.DataFrame([1, 2], [3, 4])
>>> block = Block(
...     BlockConfig(
...         title="My Block",
...         tables=[TableResult(table=df, title="My table")]
... ))
>>> removed = block.remove_table(0)
>>> removed.title
'My table'
remove_visualization(index: int) VisualizationResult[source]

Remove a visualization from the block by index.

This method updates the internal BlockConfig by deleting the visualization at the specified position. Supports negative indexing (like Python lists).

Parameters:
indexint

Index of the visualization to remove. Follows standard Python list indexing semantics.

Returns:
VisualizationResult

The removed visualization.

Raises:
IndexError

If there is no visualization at the specified index.

Examples

>>> import matplotlib.pyplot as plt
>>> from explorica.reports.core import Block, BlockConfig
>>> fig, ax = plt.subplots()
>>> block = Block(BlockConfig(visualizations=[fig]))
>>> block.remove_visualization(index=0)
VisualizationResult(...)
>>> block.block_config.visualizations
[]
>>> # Close all mpl figure after usage
>>> plt.close('all')
render_html(path: str = None, font: str | Sequence[str] = ('Arial', 'DejaVu Serif', 'DejaVu Sans', 'sans-serif'), **kwargs) str[source]

Render the block to HTML format.

This method is a thin convenience wrapper around explorica.reports.renderers.html.render_html() that allows rendering a single Block instance directly via its public API.

All parameters are forwarded to the underlying renderer without modification.

Parameters:
pathstr, optional

Directory path or full file path where the HTML output should be saved. If a directory is provided, the file name is derived automatically. If None, the rendered HTML is returned as a string without saving.

fontstr or Sequence[str], optional

Font family (or sequence of font families) used to construct the CSS font-family property for textual elements. If a sequence is provided, it is joined into a comma-separated CSS font-family declaration.

**kwargs

Additional keyword arguments forwarded to explorica.reports.renderers.html.render_html() (e.g. max_width, verbose, debug, mpl_fig_scale).

Returns:
str

Rendered HTML content as a string.

See also

explorica.reports.renderers.html.render_html

Entrypoint to render a Block or Report object into an HTML representation.

Notes

  • This method does not introduce any new rendering logic. It exists purely for ergonomic reasons, allowing HTML rendering directly from a Block instance.

  • CSS styles are applied at the block level when rendering a single block.

Examples

>>> from explorica.reports.core import Block, BlockConfig
>>> # Simple usage
>>> block = Block(BlockConfig(title="My Block"))
>>> html = block.render_html()
>>> block.render_html(path="./reports")
>>> block.render_html(path="./reports/my_block.html")
render_pdf(path: str = None, font: str = 'DejaVuSans', doc_template_kws: dict = None, **kwargs) bytes[source]

Render the block to PDF format.

This method is a thin convenience wrapper around explorica.reports.renderers.pdf.render_pdf(), enabling PDF rendering directly from a Block instance.

All parameters are forwarded to the underlying renderer without modification.

Parameters:
pathstr, optional

Directory path or full file path where the PDF output should be saved. If None, the rendered PDF is returned as bytes without saving.

fontstr, default=”DejaVuSans”

Font used for rendering text in the PDF. Can be a supported font alias or a path to a custom TTF font file.

doc_template_kwsdict, optional

Additional keyword arguments passed to ReportLab’s SimpleDocTemplate to customize page layout (e.g. margins, page size).

**kwargs

Additional keyword arguments forwarded to explorica.reports.renderers.pdf.render_pdf() (e.g. report_name, verbose, debug, mpl_fig_scale, plotly_fig_scale).

Returns:
bytes

Rendered PDF content as bytes.

See also

explorica.reports.renderers.pdf.render_pdf

Entrypoint to render a Block or Report object into an PDF representation.

Notes

  • This method provides a convenient, object-oriented interface for PDF rendering but does not alter rendering behavior.

  • Plotly visualizations are rendered as placeholders due to the static nature of the PDF format.

Examples

>>> from explorica.reports.core import Block, BlockConfig
>>> # Simple usage
>>> block = Block(BlockConfig(title="My Block"))
>>> pdf_bytes = block.render_pdf()
>>> block.render_pdf(path="./reports")
>>> block.render_pdf(path="./reports/my_block.pdf")
property typename

Return the class name.

Useful for type-checking and logging purposes.

Returns:
str

The name of the class (‘Block’).

Examples

>>> from explorica.reports.core import Block
>>> block = Block()
>>> block.typename
'Block'
class explorica.reports.core.block.BlockConfig(title: str = '', description: str = '', metrics: list[dict[str, ~typing.Any]]=<factory>, visualizations: list[Figure | Figure | VisualizationResult] = <factory>, tables: list[~typing.Sequence[~typing.Sequence[~typing.Any]] | ~typing.Mapping[str, ~typing.Sequence[~typing.Any]] | ~explorica.types.TableResult]=<factory>)[source]

Bases: object

Configuration container for a single report block in Explorica.

This dataclass stores all information necessary to render a block in a report. It includes metadata, metrics, and visualizations.

Attributes:
titlestr

The title of the block, displayed prominently in the report.

descriptionstr

A textual description of the block, providing context or explanation for the included metrics and visualizations.

metricslist of dict

A list of metric dictionaries to display in the block. Each dictionary can include keys such as: - name : str, required — name of the metric - value : Any, required — value of the metric - description : str, optional — additional context

visualizationslist of Matplotlib or Plotly figures, or VisualizationResult

A list of visualizations associated with the block. Each element can be: - matplotlib.figure.Figure — a Matplotlib figure - plotly.graph_objects.Figure — a Plotly figure - VisualizationResult — a pre-normalized visualization object Figures provided as Matplotlib or Plotly objects are automatically normalized into VisualizationResult when a Block instance is created. Users may provide raw figures or already normalized visualizations.

tableslist of array-like, mapping, or TableResult

A list of tabular results associated with the block. Each element can be: - a 1D or 2D sequence (e.g., list of lists, tuple of tuples) - a mapping (e.g., dict-like structure) - TableResult - a pre-normalized tabular container

Array-like or mapping inputs are automatically normalized into TableResult when a Block instance is created. Users may provide raw tabular data or already normalized table objects.

If a TableResult is provided, its title and description attributes are used during rendering to label and describe the table in the report output.

Notes

  • This class is primarily used internally by the Block class.

  • Normalization of figures into VisualizationResult and tabular data into TableResult occurs automatically during Block initialization. This ensures that all visual and tabular content is consistently formatted for rendering.

  • BlockConfig itself does not perform validation or normalization; this responsibility belongs to the Block class.

Examples

>>> from matplotlib import pyplot as plt
>>> from plotly import graph_objects as go
>>> from explorica.reports.core import BlockConfig
>>>
>>>
>>> fig_mpl, ax = plt.subplots()
>>> fig_plotly = go.Figure(data=go.Bar(y=[1, 2, 3]))
>>> config = BlockConfig(
...     title="Example Block",
...     description="This block shows example metrics and figures.",
...     metrics=[{"name": "Mean", "value": 5.0}],
...     visualizations=[fig_mpl, fig_plotly]
... )
>>> # Close all mpl figure after usage
>>> plt.close('all')
description: str = ''
metrics: list[dict[str, Any]]
tables: list[Sequence[Sequence[Any]] | Mapping[str, Sequence[Any]] | TableResult]
title: str = ''
visualizations: list[Figure | Figure | VisualizationResult]

explorica.reports.core.report

Report module of Explorica Reports

This module contains the Report class, which aggregates multiple Block instances into a single structured report and provides utilities for rendering, managing, and iterating over blocks.

Classes

Report(blocks=None, title=None, description=None)

Aggregates multiple report blocks into a structured report, supports rendering to HTML/PDF, block management, iteration, and safe figure handling.

Notes

  • Matplotlib figures contained in blocks are not automatically closed. To free memory after processing or rendering, call Report.close_figures().

  • Blocks passed to Report are deep-copied to ensure safety and avoid unintended side-effects on external references.

  • For consistent behavior, ensure that all blocks contain properly normalized visualizations (VisualizationResult instances).

Examples

>>> from explorica.reports import Block, BlockConfig
>>> from explorica.reports.core import Report
>>> import matplotlib.pyplot as plt
>>> import plotly.graph_objects as go
>>>
>>>
>>> # Create some figures
>>> fig1, ax1 = plt.subplots()
>>> ax1.plot([1, 2, 3], [4, 5, 6])
[...]
>>> fig2, ax2 = plt.subplots()
>>> ax2.plot([10, 20, 30], [3, 6, 9])
[...]
>>> figly = go.Figure(data=go.Bar(y=[2, 3, 1]))
>>>
>>> # Initialize blocks with metrics and visualizations
>>> block1_cfg = BlockConfig(
...     title="Block 1",
...     description="First block",
...     metrics=[{"name": "Mean", "value": 5.0}],
...     visualizations=[fig1, figly]
... )
>>> block2_cfg = BlockConfig(
...     title="Block 2",
...     description="Second block",
...     metrics=[{"name": "Std", "value": 1.2}],
...     visualizations=[fig2]
... )
>>> block1 = Block(block1_cfg)
>>> block2 = Block(block2_cfg)
>>> # Create a report with initial block
>>> report = Report(blocks=[block1], title="My Report", description="Example report")
>>> len(report)
1
>>> # Add another block in-place
>>> report += block2
>>> len(report)
2
>>> # Insert a new metric into block1
>>> block1.add_metric("Max", 10.0)
>>> # Iterate through blocks
>>> for blk in report:
...     blk.typename
'Block'
'Block'
>>> # Render report (HTML/PDF)
>>> report.render_html(path=None)
'...'
>>> report.render_pdf(path=None)
b'...'
>>> plt.close('all')
>>> plt.get_fignums()  # all report figures are closed
[]
class explorica.reports.core.report.Report(blocks: list[Block] = None, title: str = None, description: str = None)[source]

Bases: object

Aggregates multiple report blocks into a single structured report.

The Report class serves as a container for Block instances, providing utilities to compose, manage, and render aggregated reports in different formats (HTML, PDF). It supports both in-place and functional operations for adding, inserting, or removing blocks, as well as iteration and length queries like a standard Python sequence.

Parameters:
blockslist[Block], optional

Initial list[Block] instances to include in the report. If None, an empty report is created.

titlestr, optional

Title of the report.

descriptionstr, optional

Short description of the report.

Attributes:
blockslist[Block]

The list of Block instances in this report.

titlestr or None

The title of the report.

descriptionstr or None

Description of the report.

typename

Return the class name.

Methods

render_html(path=None, report_name=”report”)

Render the report to HTML format.

render_pdf(path=None, doc_template_kws=None, report_name=”report”)

Render the report to PDF format.

close_figures()

Close all active Matplotlib figures stored in this report’s blocks.

insert_block(block, index)

Insert a block at the specified index in the report.

remove_block(index)

Remove a block at the specified index.

__iadd__(other)

Add a Block or list of Blocks to the report in-place using +=.

__add__(other)

Return a new Report with other block(s) appended.

__len__()

Return the number of blocks in the report.

__iter__()

Iterate over the blocks in the report.

Notes

  • All blocks passed to the constructor are deep-copied, ensuring that modifications to blocks within the report do not affect external references.

  • Visualizations in each block are automatically normalized into VisualizationResult objects.

  • Matplotlib figures are not automatically closed. To free memory, use Report.close_figures() or ensure that Block provides a method to close its visualizations.

Examples

>>> from explorica.reports import Block, BlockConfig
>>> from explorica.reports.core import Report
>>> import matplotlib.pyplot as plt
>>> import plotly.graph_objects as go
>>>
>>>
>>> # Create some figures
>>> fig1, ax1 = plt.subplots()
>>> ax1.plot([1, 2, 3], [4, 5, 6])
[...]
>>> fig2, ax2 = plt.subplots()
>>> ax2.plot([10, 20, 30], [3, 6, 9])
[...]
>>> figly = go.Figure(data=go.Bar(y=[2, 3, 1]))
>>> # Initialize blocks with metrics and visualizations
>>> block1_cfg = BlockConfig(
...     title="Block 1",
...     description="First block",
...     metrics=[{"name": "Mean", "value": 5.0}],
...     visualizations=[fig1, figly]
... )
>>> block2_cfg = BlockConfig(
...     title="Block 2",
...     description="Second block",
...     metrics=[{"name": "Std", "value": 1.2}],
...     visualizations=[fig2]
... )
>>> block1 = Block(block1_cfg)
>>> block2 = Block(block2_cfg)
>>> # Create a report with initial block
>>> report = Report(
...     blocks=[block1], title="My Report", description="Example report")
>>> len(report)
1
>>> # Add another block in-place
>>> report += block2
>>> len(report)
2
>>> # Insert a new metric into block1
>>> block1.add_metric("Max", 10.0)
>>> # Iterate through blocks
>>> for blk in report:
...     print(blk.typename)
Block
Block
>>> # Render report (HTML/PDF)
>>> report.render_html(path=None)
'...'
>>> report.render_pdf(path=None)
b'...'
>>> plt.close('all')
>>> plt.get_fignums()  # all report figures are closed
[]
close_figures()[source]

Close all active Matplotlib figures stored in this report’s blocks.

This method iterates over all visualizations in all Block instances contained within the report and closes any Matplotlib figures to free up memory and resources.

Notes

  • Only Matplotlib figures are affected; Plotly figures or other visualization objects are ignored.

  • It is recommended to call this method once all processing or rendering with the Report instance is finished, to avoid memory leaks from lingering figure objects.

Examples

>>> from explorica.reports.core import Block, BlockConfig, Report
>>> # Simple usage
>>> block = Block(BlockConfig(title="My block"))
>>> report = Report(blocks=[block, block], title="My Report")
>>> # ... generate visualizations and render report ...
>>> report.close_figures()  # safely close all Matplotlib figures
insert_block(block: Block, index: int)[source]

Insert a block at the specified position in the report.

If index is not provided or is -1, the block is appended to the end of the report (equivalent to append).

Parameters:
blockBlock

The block to insert into the report.

indexint, optional

Position at which to insert the block. Supports negative indexing.

Examples

>>> from explorica.reports.core import Block, Report, BlockConfig
>>> # Add a single block:
>>> block1, block2, block3 = (
...     Block(BlockConfig(title="My first block")),
...     Block(BlockConfig(title="My second block")),
...     Block(BlockConfig(title="My third block"))
... )
>>> # Insert a block at the beginning:
>>> report = Report(blocks=[block1])
>>> report.insert_block(block2, index=0)
>>> report.blocks[0].block_config.title
'My second block'
>>> # Insert a block at the end (using len(report.blocks) as index):
>>> report.insert_block(block3, index=len(report.blocks))
>>> report.blocks[-1].block_config.title
'My third block'
remove_block(index: int) Block[source]

Remove a block from the report at the specified index.

This method modifies the current Report instance by removing the block at the given position. Supports negative indexing (like Python lists).

Parameters:
indexint

Position of the block to remove. Negative values count from the end (e.g., -1 removes the last block).

Returns:
Block

The removed block instance.

Raises:
IndexError

If the index is out of range.

Examples

>>> from explorica.reports.core import Block, Report
>>> block1, block2 = Block(), Block()
>>> # Remove the first block:
>>> report = Report(blocks=[block1, block2])
>>> report.remove_block(0)
<...>
>>> len(report.blocks)
1
>>> # Remove the last block using negative indexing:
>>> report.remove_block(-1)
<...>
>>> len(report.blocks)
0
render_html(path: str = None, font: str | Sequence[str] = ('Arial', 'DejaVu Serif', 'DejaVu Sans', 'sans-serif'), **kwargs) str[source]

Render the report to HTML format.

This method is a thin convenience wrapper around explorica.reports.renderers.html.render_html() and exposes the same rendering functionality directly on a Report instance.

All parameters are forwarded to the underlying renderer without modification.

Parameters:
pathstr, optional

If provided, the HTML content will be saved to this location. Can be a directory (in which case the file will be saved as "{report_name}.html") or a full file path ending with .html.

fontstr or Sequence[str], optional

Font family or sequence of font families to be applied to textual elements (title, description, metrics) in the report. If a sequence is provided, the first available font installed on the system will be used. Defaults to ("Arial", "DejaVu Serif", "DejaVu Sans", "sans-serif").

**kwargsdict

Additional parameters passed through to the underlying render_html() function. This includes, for example, report_name, max_width, mpl_fig_scale, plotly_fig_scale, verbose, debug, etc.

Returns:
str

HTML content as a string.

See also

explorica.reports.renderers.html.render_html

Entrypoint to render a Block or Report object into an HTML representation.

Notes

  • CSS is automatically applied for the report container and its blocks.

  • Font-family is determined from the font argument and propagated to all textual elements.

  • Visualizations (Matplotlib and Plotly) are rendered according to the scaling factors provided via kwargs.

  • This method does not modify the underlying Report instance.

Examples

>>> from explorica.reports.core import Block, BlockConfig, Report
>>> # Simple usage
>>> block = Block(BlockConfig(title="My block"))
>>> report = Report(blocks=[block, block], title="My Report")
>>> # Render HTML without saving
>>> html_content = report.render_html()
>>> # Render and save to a directory (file name derived from `report_name`)
>>> report.render_html(
...     path="./output", report_name="customer_report")
>>> # Render and save to a full file path
>>> report.render_html(path="./output/my_report.html")
render_pdf(path: str = None, font: str = 'DejaVuSans', doc_template_kws: dict = None, **kwargs) bytes[source]

Render the report to PDF format.

This method is a thin convenience wrapper around explorica.reports.renderers.pdf.render_pdf() and exposes the same rendering functionality directly on a Report instance.

All parameters are forwarded to the underlying renderer without modification.

Parameters:
pathstr or None, optional

Directory path or full file path where the PDF report should be saved. - If a directory is provided, the report is saved as f"{report_name}.pdf" inside that directory. - If a full file path ending with .pdf is provided, the report is saved to that exact location. If None, the rendered PDF is returned as bytes without saving.

doc_template_kwsdict, optional

Keyword arguments passed directly to reportlab.platypus.SimpleDocTemplate to control PDF layout (e.g., margins, page size). Provides full access to all currently supported customization options.

report_namestr, default=”report”

Base name used for the output file when path is a directory.

Returns:
bytes

Rendered PDF content as bytes.

See also

explorica.reports.renderers.pdf.render_pdf

Entrypoint to render a Block or Report object into an PDF representation.

Notes

This method exposes the full capabilities of the PDF renderer. Users can rely on this method to access all functionality currently implemented in explorica.reports.renderers.render_pdf.

Examples

>>> from explorica.reports.core import Block, BlockConfig, Report
>>> # Simple usage
>>> block = Block(BlockConfig(title="My block"))
>>> report = Report(blocks=[block, block], title="My Report")
>>> pdf_bytes = report.render_pdf()
>>> report.render_pdf(path="output/")
>>> report.render_pdf(
...     path="output/my_report.pdf",
...     doc_template_kws={"pagesize": A3}
... )
property typename

Return the class name.

Useful for type-checking and logging purposes.

Returns:
str

The name of the class (‘Report’).

Examples

>>> from explorica.reports.core import Report
>>> report = Report()
>>> report.typename
'Report'