Formualizer Docs
Reference

Python API Reference

Comprehensive documentation for the Formualizer Python bindings.

The formualizer Python package provides a high-performance interface to the Rust formula engine, supporting both simple evaluation and complex workbook management.

Workbook API

The Workbook class is the primary entry point for managing spreadsheet state and evaluation.

  • Workbook(mode='shared', config=None): Initialize a new workbook.
  • load_path(path: str): Load a workbook from a file path.
  • from_path(path: str): (Alias) Load a workbook from a file path.
  • add_sheet(name: str): Add a new sheet.
  • sheet(name: str): Get a handle to a specific sheet.
  • set_value(sheet: str, row: int, col: int, value: Any): Set a literal value at a coordinate.
  • set_formula(sheet: str, row: int, col: int, formula: str): Set a formula at a coordinate.
  • evaluate_cell(sheet: str, row: int, col: int) -> Any: Evaluate and return a cell value.
  • evaluate_all(): Re-evaluate all dirty cells in the workbook.
  • evaluate_cells(targets: List[Tuple[str, int, int]]): Evaluate a specific list of target cells.
  • set_values_batch(row: int, col: int, grid: List[List[Any]]): Efficiently set a block of values.
  • set_formulas_batch(row: int, col: int, grid: List[List[str]]): Efficiently set a block of formulas.

Interruptible recalculation

  • Workbook.begin_recalc(*, collect_deltas=True, max_delta_records=1024, priority=None) -> RecalcJob
  • RecalcJob.step(budget_ms=None, *, cancel=None) -> StepReport
  • RecalcJob.prioritize(ranges), cancel() -> StepReport | None, and active (property)
  • RecalcJob.iter(budget_ms=5) yields reports through the terminal report; the job is also a context manager that cancels on exit.
  • Workbook.recalc(budget_ms=5, *, on_step=None, priority=None) -> RecalcOutcome
  • Workbook.evaluate_async(budget_ms=5, *, on_progress=None, priority=None) returns an awaitable yielding RecalcResult | None (None on cooperative cancellation).
  • Workbook.has_active_recalc_job and Workbook.is_poisoned (properties), has_pending_in_rect(sheet, r0, c0, r1, c1) and pending_cells_in_rect(sheet, r0, c0, r1, c1)

All coordinates are 1-based and inclusive, including priority, changed and pending rectangles: (sheet_name, r0, c0, r1, c1). Pass a list of these rectangles as priority or ranges. None means no soft deadline; zero still permits an atomic unit to finish.

StepReport is immutable and contains phase (BuildingGraph, Scheduling, Evaluating, Finished, Cancelled), progress, step_computed, step_elapsed_ms, changed, overflow_sheets, longest_unit and result. Progress has pass_ (Python's pass is reserved), completed_in_pass, scheduled_in_pass, cumulative, total_exact, staged_remaining and priority_pending. Changed/pending rectangles are conservative; overflow identifies sheets to repaint. Pending queries expose raw dirtiness; volatile and iterative formulas may be dirty again after Finished. Only Finished carries a result (computed_vertices, cycle_errors, elapsed_ms). A longest unit carries kind, representative_cell, vertex_count and elapsed_ms.

RecalcOutcome.status is Finished, Cancelled or Paused. A paused outcome carries job for later stepping; only Finished carries result. Returning exactly False from on_step(report) pauses, unless the report is terminal. Callback exceptions propagate; a synchronous callback exception leaves the reached lifecycle state intact. Keep the job API for explicit ownership when callbacks can fail. Async callback exceptions cancel any remaining job before propagation.

evaluate_async reserves its driver before its first await. While another async driver is in admission, running, delivering progress or cleaning up—or a manual job is pending/active—a second driver raises RecalcAlreadyPendingError promptly without waiting for the engine lock. A new driver may begin after the prior driver returns. Native admission, steps, active-state queries and cancellation cleanup run on workers, so lock contention never blocks the event-loop thread inside the driver. Cancellation during admission waits for that owned admission to finish, cancels any job it admitted, and then re-raises CancelledError. A manual begin_recalc is also refused while an async driver owns the reservation.

CancelToken() provides cancel() and cancelled. Cancellation is cooperative at installation boundaries. Stale job handles raise NoActiveJobError when driven, even if another job has begun; their active property is False. A step evaluation error ends the job and keeps the existing ExcelEvaluationError fields.

RecalcJobError has subclasses NoActiveJobError, RecalcAlreadyPendingError (explicit attribute), and EnginePoisonedError. Existing evaluate_all, evaluate_cell and evaluate_cells raise RecalcJobActiveError (a subclass of ExcelEvaluationError) while a job is active. Internal Rust unwinds preserve workbook lock poisoning; is_poisoned reports this health state without recovering the lock. Discard the workbook. A contained host panic has extra={"kind": "FunctionPanicked", "function": ..., "message": ...} on ExcelError, ExcelEvaluationError and error dictionaries returned from cells; LiteralValue.error_extra exposes the same payload. The function name also identifies source resolvers (for example resolver:resolve_source_scalar:Sales). Ordinary raising Python functions keep their existing Value-error behavior.

See Interruptible Recalculation for sync and async examples and budget limits.

Custom Functions

  • register_function(name: str, callback: Callable, options: dict): Register a Python function for use in formulas.
  • unregister_function(name: str): Remove a registered function.
  • list_functions() -> List[str]: List all available functions.

History and Undo

  • set_changelog_enabled(enabled: bool): Enable or disable tracking of changes.
  • begin_action(description: str): Group following changes into a single undoable action.
  • end_action(): Close the current action group.
  • undo(): Revert the last action.
  • redo(): Re-apply the last undone action.

SheetPort

SheetPortSession manages high-level data exchange using a manifest to define input/output mappings.

  • SheetPortSession(workbook: Workbook, manifest): Create a session from a formualizer.sheetport.Manifest or a canonical manifest dict.
  • from_manifest_yaml(yaml: str, workbook: Workbook): Create a session from a YAML string.
  • from_manifest_path(manifest_path: str, workbook_path: str, backend: str | None = None): Open a manifest file and a workbook file.
  • read_inputs() -> dict: Read current values of all defined input ports.
  • read_outputs() -> dict: Read current values of all defined output ports.
  • write_inputs(data: dict): Update workbook values via input ports.
  • evaluate_once(*, freeze_volatile=False, rng_seed=None, deterministic_timestamp_utc=None, deterministic_timezone=None) -> dict: Recalculate and return the output values.
  • manifest -> dict: The bound manifest (property).
  • describe_ports() -> dict: Get metadata about defined ports.

formualizer.sheetport builds manifests in code: Manifest(id, *, ports, name=None, ...), Input / Output(id, location, *, type=None, schema=None, ...), locations name() and layout(), schemas range_of(), record_of() and table_of() with column(). Manifest.to_dict(), to_yaml(), from_dict() and from_yaml() convert between forms.

Parser and Tokenizer

  • formualizer.Tokenizer(formula: str): Tokenize a formula.
  • formualizer.Parser(formula: str): Parse a formula into an AST.

Exceptions

  • SheetPortError: Base class for SheetPort-related errors.
  • SheetPortManifestError: Raised when a manifest is invalid or cannot be parsed.
  • SheetPortConstraintError: Raised when an input value violates a manifest constraint.

See Also

On this page