Examples

Start with the smallest public examples first. They show the intended import style and the current shared workflow surface.

Numeric Normalization

This example shows how Buffalo Core normalizes flexible numeric inputs into stable NumPy arrays and Python scalar values.

Run it with:

uv run python examples/numeric_normalization.py
"""Show how Buffalo Core normalizes flexible numeric inputs."""

from __future__ import annotations

import numpy as np

from buffalo_core.numeric import (
    as_float_array,
    as_float_scalar,
    as_int_array,
    as_int_scalar,
)


def main() -> None:
    """Print normalized values and their resulting runtime types."""
    float_samples = as_float_array([0.0, 0.5, 1.0])
    int_ids = as_int_array((1, 2, 3, 4))
    single_angle = as_float_scalar(np.float64(5.0))
    single_index = as_int_scalar(np.int64(7))

    print("float_samples:", float_samples, float_samples.dtype)
    print("int_ids:", int_ids, int_ids.dtype)
    print("single_angle:", single_angle, type(single_angle).__name__)
    print("single_index:", single_index, type(single_index).__name__)


if __name__ == "__main__":
    main()

Expected output:

float_samples: [0.  0.5 1. ] float64
int_ids: [1 2 3 4] int32
single_angle: 5.0 float
single_index: 7 int

Structured Schema Metadata

This example shows how Buffalo Core stores GUI-friendly field metadata directly on dataclass fields while preserving separate serialized values and display labels for enum-like choices.

Run it with:

uv run python examples/schema_metadata_workflow.py
"""Show how Buffalo Core defines GUI-friendly schema metadata."""

from __future__ import annotations

from dataclasses import dataclass, field

from buffalo_core.schema import SchemaChoice, SchemaField, schema_field_metadata


@dataclass(slots=True)
class SolverSpec:
    """Tiny schema example using shared field metadata."""

    formulation: str = field(
        default="hess_smith",
        metadata=SchemaField(
            value_kind="enum",
            required=False,
            label="Formulation",
            order=10,
            short_help="Select the solver formulation.",
            default="hess_smith",
            choices=(SchemaChoice(value="hess_smith", label="Hess-Smith"),),
        ).to_metadata(),
    )


def main() -> None:
    """Print one small example of structured schema metadata."""
    metadata = schema_field_metadata(SolverSpec)["formulation"]
    print("label:", metadata["label"])
    print("default:", metadata["default"])
    print("choices:", metadata["choices"])


if __name__ == "__main__":
    main()

Expected output:

label: Formulation
default: hess_smith
choices: ({'value': 'hess_smith', 'label': 'Hess-Smith'},)

Schema Tree Inspection

This example shows how Buffalo Core can expose one small nested tree view of dataclass-backed schema structure for editor or inspection workflows.

Run it with:

uv run python examples/schema_tree_workflow.py
"""Inspect nested dataclass schema structure with Buffalo Core."""

from __future__ import annotations

from dataclasses import dataclass, field

from buffalo_core.schema import SchemaField, schema_tree


@dataclass(slots=True)
class SolverSettings:
    """Simple nested schema used by the tree example."""

    formulation: str = field(
        default="hess_smith",
        metadata=SchemaField(
            value_kind="enum",
            required=False,
            label="Formulation",
            order=10,
            short_help="Potential-flow formulation.",
            default="hess_smith",
            choices=("hess_smith",),
        ).to_metadata(),
    )


@dataclass(slots=True)
class ExampleCase:
    """Small top-level schema used by the tree example."""

    name: str = field(
        default="example",
        metadata=SchemaField(
            value_kind="string",
            required=True,
            label="Name",
            order=10,
            short_help="Case identifier.",
        ).to_metadata(),
    )
    solver: SolverSettings = field(
        default_factory=SolverSettings,
        metadata=SchemaField(
            value_kind="object",
            required=True,
            label="Solver",
            order=20,
            short_help="Solver configuration.",
        ).to_metadata(),
    )


def main() -> None:
    """Print one compact nested schema summary."""
    tree = schema_tree(ExampleCase)
    print(tree.class_name)
    for field_info in tree.fields:
        print(
            f"  {field_info.name}: "
            f"type={field_info.type_name!r} optional={field_info.optional}"
        )
        if field_info.object_schema is not None:
            print(f"    child={field_info.object_schema.class_name}")


if __name__ == "__main__":
    main()

Expected output:

ExampleCase
  name: type='str' optional=False
  solver: type='SolverSettings' optional=False
    child=SolverSettings

Structured Diagnostics

This example shows how one workflow can return a primary value together with structured diagnostics using OperationResult.

Run it with:

uv run python examples/diagnostics_workflow.py
"""Show how Buffalo Core returns values together with diagnostics."""

from __future__ import annotations

from buffalo_core.diagnostics import (
    Diagnostic,
    DiagnosticLocation,
    DiagnosticReport,
    DiagnosticSeverity,
    OperationResult,
)

_MIN_PANEL_COUNT = 4


def normalize_panel_count(panel_count: int) -> OperationResult[int]:
    """Clamp one panel count and report the adjustment as a warning."""
    diagnostics: list[Diagnostic] = []
    normalized = panel_count
    if panel_count < _MIN_PANEL_COUNT:
        normalized = _MIN_PANEL_COUNT
        diagnostics.append(
            Diagnostic(
                severity=DiagnosticSeverity.WARNING,
                code="panel_count.clamped",
                message="Panel count increased to the minimum supported value.",
                location=DiagnosticLocation(field_path="panel_count"),
            )
        )
    return OperationResult(
        value=normalized,
        diagnostics=DiagnosticReport(entries=tuple(diagnostics)),
    )


def main() -> None:
    """Run one small workflow that returns a value with diagnostics."""
    result = normalize_panel_count(2)
    print("value:", result.value)
    print("has_warnings:", result.has_warnings)
    for diagnostic in result.diagnostics.entries:
        print(
            f"{diagnostic.severity}: {diagnostic.code} -> {diagnostic.message}"
        )


if __name__ == "__main__":
    main()

Expected output:

value: 4
has_warnings: True
warning: panel_count.clamped -> Panel count increased to the minimum supported value.

Buffalo Project Integration

Buffalo Core is meant to be used directly by Buffalo projects and by thin project-local facades built on top of it.

From Buffalo Wings

Buffalo Wings can share the same low-level typing and normalization behavior while keeping its own local import surface:

from buffalo_wings.internal.numeric import as_float_array
from buffalo_wings.type_aliases import FloatArray


def normalize_coordinates(values: FloatArray) -> FloatArray:
    return as_float_array(values)

From Buffalo Panel

Buffalo Panel can rely on Buffalo Core diagnostics when a workflow needs to return both a computed value and machine-readable warnings:

from buffalo_core.diagnostics import (
    Diagnostic,
    DiagnosticReport,
    DiagnosticSeverity,
    OperationResult,
)


def assemble_strength_count(count: int) -> OperationResult[int]:
    diagnostics = ()
    if count <= 0:
        diagnostics = (
            Diagnostic(
                severity=DiagnosticSeverity.ERROR,
                code="strength_count.invalid",
                message="Strength count must be positive.",
            ),
        )
    return OperationResult(
        value=count,
        diagnostics=DiagnosticReport(entries=diagnostics),
    )