API reference¶
Monitoring¶
Monitoring helpers for logging failures, output streams, and Git state.
- snippets.monitoring.append_git_state_snapshot(log_path, *, section='POINT', repo_dir=None, anchor_paths=None, max_parent_levels=3, max_diff_bytes=262144, encoding='utf-8')[source]¶
Append git state metadata to a plain-text logfile.
- Parameters:
log_path (Path | str) – Log file target.
section (Literal["START", "END", "POINT"], optional) – Snapshot label.
repo_dir (Path | str | None, optional) – Directory to start git discovery from.
anchor_paths (Sequence[Path | str] | None, optional) – Paths expected to be tracked in the target repository.
max_parent_levels (int, optional) – Number of parent directories to inspect when repo_dir is omitted.
max_diff_bytes (int, optional) – If staged + unstaged patch size is larger than this threshold, the function logs –stat output instead of full patch output.
encoding (str, optional) – File encoding used for writing and size accounting.
- Return type:
None
- snippets.monitoring.git_state_context(log_path, *, snapshot_timing='both', repo_dir=None, anchor_paths=None, max_parent_levels=3, max_diff_bytes=262144, encoding='utf-8')[source]¶
Context manager that writes START/END git state snapshots.
Example
- with git_state_context(“run.log”, snapshot_timing=”both”):
run_workflow()
- Parameters:
log_path (Path | str)
snapshot_timing (Literal['start', 'end', 'both'])
repo_dir (Path | str | None)
anchor_paths (Sequence[Path | str] | None)
max_parent_levels (int)
max_diff_bytes (int)
encoding (str)
- snippets.monitoring.mail_traceback_wrapper(to_address, subject_tag=None, from_address=None)[source]¶
Return a decorator that emails tracebacks through localhost SMTP.
- Parameters:
to_address (str) – Recipient email address.
subject_tag (str) – Optional prefix added to the error subject.
from_address (str) – Optional sender address.
- snippets.monitoring.pipe_output_and_git_state_log(log_path, mode='a', *, snapshot_timing='both', repo_dir=None, anchor_paths=None, max_parent_levels=3, max_diff_bytes=262144, encoding='utf-8')[source]¶
Pipe stdout/stderr and log git state snapshots in one context.
Example
- with pipe_output_and_git_state_log(“run.log”, mode=”w”):
print(“workflow started”) run_workflow()
- Parameters:
log_path (Path | str)
mode (Literal['a', 'w'])
snapshot_timing (Literal['start', 'end', 'both'])
repo_dir (Path | str | None)
anchor_paths (Sequence[Path | str] | None)
max_parent_levels (int)
max_diff_bytes (int)
encoding (str)
Debugging¶
Debugging helpers for interactive analysis and small workflow scripts.
- class snippets.debugging.Diagnostics(enabled=False, outdir='debug', only=None, *, _prefix=None)[source]¶
Bases:
objectSmall opt-in writer for diagnostic artifacts.
Use this in external scripts or home-brewed workflow code when plots, reports, or snapshots are useful for debugging an operation.
- Parameters:
enabled (bool)
outdir (Path | str)
only (Iterable[str] | None)
_prefix (str | None)
Monkeypatch¶
Context helpers for applying temporary monkeypatches.
- snippets.monkeypatch.gatekeeper(module_version, rules)[source]¶
Checks whether a patch should be applied
Use with a list of dict like:
[{ "version": "2.3", "comparator": operator.lt, "action": "skip"}, { "version": "3", "comparator": operator.ge, "action": "warn" }]
- Parameters:
module_version (str) – current version of the patched module
rules (dict) – Requires keys “comparator”, “version”, and “action”.
- Returns:
rules[“action”] if condition is met, else None
- Return type:
str
- snippets.monkeypatch.monkeypatch(dictlist)[source]¶
Constructs a patched context
Patching the backend of foreign functions quickly leads to inconsistencies. Using the patch only within a chosen context limits side effects.
Optionally, have
gatekeeper()manage for which version to apply the patch, to warn about compatibility issues, or to raise an error.Use like:
patchdicts = [{ "module": mod1, "target": "obj1", "replacement": patch1, "version": base_mod1.__version__, # optional "rules": rules1}, # optional { "module": mod2, "target": "obj2", "replacement": patch2 }] with monkeypatch(patchdicts): <your code>
- Parameters:
dictlist (list[dict]) – Requires keys “module”, “target”, and “replacement”.
Parallel¶
Small threading helpers.
- snippets.parallel.same_task_threads(task_func, n_workers, result_queue=None)[source]¶
Create workers and return the queue used to assign tasks.
- Parameters:
task_func (callable) – Function called for each queued task tuple.
n_workers (int) – Number of requested workers.
result_queue (queue.Queue, optional) – Queue in which to drop results. Defaults to None.
- Returns:
Task queue. Put
Nonein the queue to skip work; task tuples are expanded astask_func(*next_task).- Return type:
queue.Queue
Xarray utilities¶
Utilities for inspecting and slicing xarray objects.
- snippets.xr_utils.build_enc_dict__cmpr_f4(ds)[source]¶
Build NetCDF compression encoding for multi-dimensional data variables.
- Parameters:
ds (Dataset)
- Return type:
dict
- snippets.xr_utils.get_chunk_number(da, dim, coords)[source]¶
Return chunk indices containing one or more coordinates along a dimension.
- Parameters:
da (DataArray)
dim (Hashable)
coords (Any)
- Return type:
list[Any]
- snippets.xr_utils.print_xarray_dataset_summary(obj, *, label=None, prefix='[xarray-debug]', file=None)[source]¶
Print
xarray_dataset_summary()to a file-like object.- Parameters:
obj (Dataset | DataArray)
label (str | None)
prefix (str)
file (TextIO | None)
- Return type:
None
- snippets.xr_utils.sel_chunks_by_coord_range(da, **dim_intervals)[source]¶
Select chunk ranges that contain coordinate intervals for each dimension.
- Parameters:
da (DataArray)
- Return type:
DataArray
Package helpers¶
Small Python helpers for interactive analysis and workflow scripts.
- snippets.is_notebook()[source]¶
Return whether the current interpreter appears to be a notebook shell.
- Return type:
bool
- snippets.precision(uncertainty)[source]¶
Calculate number of digits to state
Use for formating numbers, e.g., in print statements.
Example¶print(f"{value:.{precision(uncertainty)}f}")
- Parameters:
uncertainty (float) – Uncertainty estimate.
- Returns:
Number of “significant” decimal digits.
- Return type:
int