Schema⚓︎
schema
⚓︎
Stable public schema façade.
The implementation lives in focused internal compiler and engine modules.
Projects should continue importing :class:RowTable, :class:ColumnTable,
and :class:TableFields from :mod:talika or :mod:talika.schema.
BaseTable
⚓︎
Bases: TableRecord, TableFields
Shared schema lifecycle for row- and column-oriented tables.
Subclasses declare fields and may override lifecycle hooks such as
:meth:validate_record. Users normally subclass :class:RowTable or
:class:ColumnTable instead of using this class directly.
Attributes:
-
table_transformer–Optional reusable transformer object.
-
output_model–Optional callable used by the default
build_output. -
unknown_fields–Policy for table labels not declared by the schema.
-
inapplicable_fields–Policy for populated variant fields that do not apply to the selected variant.
Info
Public parsing APIs live on RowTable and ColumnTable because
orientation determines how labels and records are found.
variant
classmethod
⚓︎
Register a schema subclass for one discriminator value.
The decorated class must inherit from the base schema. Its inherited fields remain common to every record, while newly declared fields are required, parsed, and validated only for records selecting that variant.
Registration deliberately uses ordinary Python values. If a
discriminator_field has a parser, register the parsed value rather
than the raw table text.
Parameters:
-
value(Any) –Parsed discriminator value that should select the decorated schema subclass.
Returns:
variant_for
classmethod
⚓︎
Return the registered schema class for one parsed selector value.
This is especially useful with declarative discriminator()
mappings, whose concrete schema classes are generated by the package.
A missing value raises KeyError just like an ordinary mapping.
Parameters:
-
value(Any) –Parsed discriminator value.
Returns:
Info
Prefer this method over relying on generated variant class names.
describe
classmethod
⚓︎
describe() -> TableContract
Return an immutable machine-readable description of this schema.
The import is local to keep the parser core independent from the introspection dataclasses during class creation.
Returns:
-
TableContract–Immutable machine-readable table contract.
parse
classmethod
⚓︎
parse(
datatable: RawTable | TableData,
*,
context: Mapping[str, Any] | ParseContext | None = None,
error_mode: str = "first",
) -> list[TableT]
Parse a table into validated records for a concrete orientation.
Parameters:
-
datatable(RawTable | TableData) –Raw string rows or source-aware
TableData. -
context(Mapping[str, Any] | ParseContext | None, default:None) –Optional project data or existing parse context.
-
error_mode(str, default:'first') –"first"or"collect".
Returns:
-
list[TableT]–Validated instances of the concrete schema class.
Raises:
-
NotImplementedError–Always, because
BaseTablelacks an orientation.
Warning
Use RowTable or ColumnTable. This base method documents the
common signature only.
parse_as
classmethod
⚓︎
parse_as(
datatable: RawTable | TableData,
output_model: Callable[..., OutputT] | None = None,
*,
context: Mapping[str, Any] | ParseContext | None = None,
error_mode: str = "first",
) -> list[OutputT] | list[Any]
Parse a table and convert each validated record.
Parameters:
-
datatable(RawTable | TableData) –Raw string rows or source-aware
TableData. -
output_model(Callable[..., OutputT] | None, default:None) –Optional callable receiving record fields as keyword arguments. When omitted, use configured output hooks.
-
context(Mapping[str, Any] | ParseContext | None, default:None) –Optional project data or existing parse context.
-
error_mode(str, default:'first') –"first"or"collect".
Returns:
Raises:
-
NotImplementedError–Always, because
BaseTablelacks an orientation.
Warning
Use RowTable or ColumnTable. This base method documents the
common signature only.
validate
classmethod
⚓︎
validate(
datatable: RawTable | TableData,
*,
context: Mapping[str, Any] | ParseContext | None = None,
) -> ValidationResult[TableT]
Validate table data through a concrete orientation.
Parameters:
-
datatable(RawTable | TableData) –Raw string rows or source-aware
TableData. -
context(Mapping[str, Any] | ParseContext | None, default:None) –Optional project data or existing parse context.
Returns:
-
ValidationResult[TableT]–A non-raising validation result containing records or diagnostics.
Raises:
-
NotImplementedError–Always, because
BaseTablelacks an orientation.
validate_record
⚓︎
validate_record(context: ParseContext) -> None
Validate one parsed record after fields and references are available.
Parameters:
-
context(ParseContext) –Parse context for the current operation.
Raises:
-
TableError–For custom source-aware diagnostics.
-
Exception–Any other exception is wrapped as a record validation failure.
validate_records
classmethod
⚓︎
validate_records(records: Sequence[BaseTable], context: ParseContext) -> None
Validate relationships across all parsed records.
Parameters:
-
records(Sequence[BaseTable]) –Validated records from one table.
-
context(ParseContext) –Parse context for the current operation.
Raises:
-
TableError–For custom source-aware diagnostics.
-
Exception–Any other exception is wrapped as a table validation failure.
Info
This hook runs after local references are resolved, so validators can inspect linked records.
build_output
classmethod
⚓︎
build_output(record: BaseTable, context: ParseContext) -> Any
Convert one validated schema record to its public result object.
The default implementation returns the schema record unchanged unless
output_model is configured, in which case it calls that model with
the record fields as keyword arguments. Projects may override this
hook for custom constructors, selected fields, context dependencies,
or factory services.
Parameters:
-
record(BaseTable) –Validated schema record.
-
context(ParseContext) –Parse context for the current operation.
Returns:
-
Any–Public object returned by
parse_as()for this record.
Info
parse() returns schema records without calling this hook.
parse_as() uses it only when no explicit output model is
supplied.
transform_table
classmethod
⚓︎
transform_table(table: TableData, context: ParseContext) -> TableData
Return the source-aware table that should be parsed by the schema.
The default implementation delegates to table_transformer when a
schema declares one; otherwise it returns the table unchanged. A
project may override this hook for a table shape or grammar that does
not fit a reusable transformer.
Implementations must return :class:TableData. Reuse existing cells
and create changed values with :meth:TableCell.with_value so later
errors continue to identify the original feature-file cell.
Parameters:
-
table(TableData) –Source-aware table after raw input normalization.
-
context(ParseContext) –Parse context for the current operation.
Returns:
-
TableData–Source-aware table consumed by orientation-specific parsing.
Warning
Returning raw rows loses source information and is rejected by the parser lifecycle.
_accepted_labels
classmethod
⚓︎
_declared_by_label
classmethod
⚓︎
_cell_for_field
classmethod
⚓︎
Return the source cell for a field using its label or aliases.
Parameters:
-
declared(Field) –Field declaration to locate.
-
cells_by_label(Mapping[str, TableCell]) –Mapping from actual table labels to source cells.
Returns:
-
TableCell | None–Matching source cell, or
Nonewhen the field is absent.
Info
Alias lookup preserves the distinction between an omitted field and an explicit empty cell.
_validate_table_labels
classmethod
⚓︎
Validate unknown labels and canonical/alias duplication.
Parameters:
-
label_cells(Sequence[TableCell]) –Source cells containing labels for one table orientation.
-
errors(DiagnosticCollector) –Optional collection sink for recoverable diagnostics.
Raises:
-
TableError–In fail-fast mode when an invalid label is found.
Info
Canonical/alias duplication is checked per schema and per variant
so a table cannot provide both Headline and its alias Title
for the same applicable field.
_select_record_schema
classmethod
⚓︎
_select_record_schema(
cells_by_label: Mapping[str, TableCell],
*,
parse_context: ParseContext,
item_id: Any | None,
errors: DiagnosticCollector,
) -> tuple[type[BaseTable] | None, dict[str, Any]]
Select one record schema and return parsed selector values.
Parameters:
-
cells_by_label(Mapping[str, TableCell]) –Mapping from table labels to cells for one record.
-
parse_context(ParseContext) –Parse context for the current operation.
-
item_id(Any | None) –Current record ID when available.
-
errors(DiagnosticCollector) –Optional collection sink for recoverable diagnostics.
Returns:
-
type[BaseTable] | None–(record_schema, parsed_selector_values).record_schemais -
dict[str, Any]–Nonewhen selector parsing failed in collect mode.
Warning
The discriminator parser runs before variant lookup. Registered variant keys must match parsed values, not raw table text.
_reject_inapplicable_values
classmethod
⚓︎
_reject_inapplicable_values(
record_cls: type[BaseTable],
cells_by_label: Mapping[str, TableCell],
*,
item_id: Any | None,
errors: DiagnosticCollector,
) -> dict[str, Any]
Apply policy to values belonging to another selected variant.
Variant tables often include the union of all possible rows or columns. An empty cell is therefore harmless, but a non-empty cell for a field that the selected variant does not declare usually indicates a typo or a misunderstood table.
Parameters:
-
record_cls(type[BaseTable]) –Variant schema selected for the current record.
-
cells_by_label(Mapping[str, TableCell]) –Mapping from table labels to cells for one record.
-
item_id(Any | None) –Current record ID when available.
-
errors(DiagnosticCollector) –Optional collection sink for recoverable diagnostics.
Returns:
Info
Empty inapplicable cells are ignored so one table can contain the union of variant fields without requiring every record shape to populate every column or row.
_parse_context
classmethod
⚓︎
_parse_context(context: Mapping[str, Any] | ParseContext | None) -> ParseContext
Normalize user-supplied parse context.
Parameters:
-
context(Mapping[str, Any] | ParseContext | None) –None, a mapping, or an existingParseContext.
Returns:
-
ParseContext–A
ParseContextinstance.
Raises:
-
TableError–If the context cannot be treated as a mapping.
Info
Wrapping context errors in TableError keeps public parse
failures consistent with table diagnostics.
_validate_error_mode
classmethod
⚓︎
_validate_error_mode(error_mode: str) -> ErrorMode
Normalize the public failure strategy before parsing begins.
Parameters:
-
error_mode(str) –Public parser failure strategy.
Raises:
-
ValueError–If
error_modeis not"first"or"collect".
Warning
This is an API misuse check rather than a table diagnostic, so it
raises ValueError directly.
_report
staticmethod
⚓︎
_report(
error: TableError, errors: DiagnosticCollector, *, allow_warning: bool = False
) -> object
Raise immediately or append one recoverable diagnostic.
Parameters:
-
error(TableError) –Structured diagnostic to report.
-
errors(DiagnosticCollector) –Collector containing the active error mode and diagnostics.
-
allow_warning(bool, default:False) –Whether a warning may continue without producing a value. Only validation hooks enable this path.
Returns:
-
object–Internal invalid sentinel when the error is collected.
Raises:
-
TableError–In fail-fast mode.
Info
Returning a sentinel lets parsing continue safely while skipping only the invalid value or record.
_raise_collected
staticmethod
⚓︎
Raise the public aggregate after all safe validation has run.
Parameters:
-
errors(DiagnosticCollector) –Active lifecycle diagnostic collector.
Raises:
-
TableErrors–If
errorscontains one or more diagnostics.
Warning
Dependent lifecycle stages stop after collected structural errors so users do not receive noisy secondary failures.
_prepare_table
classmethod
⚓︎
_prepare_table(
datatable: RawTable | TableData, parse_context: ParseContext
) -> TableData
Create source cells, run transformation, and validate its contract.
Parameters:
-
datatable(RawTable | TableData) –Raw rows or already source-aware table.
-
parse_context(ParseContext) –Parse context for the current operation.
Returns:
-
TableData–Transformed source-aware table.
Raises:
-
TableError–If raw or transformed tables are empty, the transformer fails, or the transformer returns a non-TableData value.
Info
Both the source and transformed table are checked for minimum shape so transformation cannot produce an unparsable empty table.
_value_for
classmethod
⚓︎
_value_for(
declared: Field,
*,
present: bool,
cell: TableCell | None,
parse_context: ParseContext,
item_id: Any | None,
source_uri: str | None = None,
errors: DiagnosticCollector,
) -> Any
Resolve one declared field from a present or missing cell.
Parameters:
-
declared(Field) –Field declaration being resolved.
-
present(bool) –Whether any canonical label or alias appeared.
-
cell(TableCell | None) –Source cell when the field is present.
-
parse_context(ParseContext) –Parse context for the current operation.
-
item_id(Any | None) –Current record ID when available.
-
source_uri(str | None, default:None) –Source document URI when no cell supplies it.
-
errors(DiagnosticCollector) –Optional collection sink for recoverable diagnostics.
Returns:
-
Any–Parsed/default field value, or the internal invalid sentinel when
-
Any–collect mode records a failure.
Raises:
-
RuntimeError–If callers mark a field present without passing a source cell.
-
TableError–In fail-fast mode for missing/empty/parser failures.
Warning
Missing optional fields and explicit empty cells are distinct. Defaults run only when the field label is absent.
_check_table
classmethod
⚓︎
_check_table(table: TableData) -> None
Reject tables that cannot contain schema labels.
Parameters:
-
table(TableData) –Source-aware table to validate.
Raises:
-
TableError–If the table or its label row/column is empty.
Info
Orientation-specific parsers perform rectangularity checks after this minimum shape validation.
_validate_id
classmethod
⚓︎
Require a parsed identity value that can safely key indexes.
_reject_duplicates
classmethod
⚓︎
Reject repeated table labels using original source locations.
Parameters:
-
label_cells(Sequence[TableCell]) –Cells containing labels for the active orientation.
-
errors(DiagnosticCollector) –Optional collection sink for recoverable diagnostics.
Raises:
-
TableError–In fail-fast mode when a duplicate is found.
Warning
Duplicate labels are rejected before field lookup because otherwise the parser would have to choose between multiple source cells for the same schema field.
_validate_required_presence
classmethod
⚓︎
_validate_required_presence(
labels: Sequence[str], errors: DiagnosticCollector, *, source_uri: str | None = None
) -> None
Validate required fields when a table contains no records.
Parameters:
-
labels(Sequence[str]) –Labels present in the table's label row or column.
-
errors(DiagnosticCollector) –Optional collection sink for recoverable diagnostics.
-
source_uri(str | None, default:None) –Source document URI for missing-field diagnostics.
Raises:
-
TableError–In fail-fast mode when a required field is absent.
Info
Normal record parsing reports missing required fields per record. This helper handles empty data tables where no record loop runs.
_parse_record_values
classmethod
⚓︎
_parse_record_values(
record_cls: type[BaseTable],
cells_by_label: Mapping[str, TableCell],
*,
parse_context: ParseContext,
item_id: Any | None,
errors: DiagnosticCollector,
parsed_values: Mapping[str, Any] | None = None,
parsed_sources: Mapping[str, TableCell] | None = None,
) -> tuple[bool, dict[str, Any], dict[str, TableCell], Any | None]
Parse applicable fields for one record schema.
_record_from_values
classmethod
⚓︎
_record_from_values(
values: dict[str, Any],
*,
cells: Mapping[str, TableCell],
row: int | None = None,
column: int | None = None,
item_id: Any | None = None,
extras: Mapping[str, Any] | None = None,
) -> BaseTable
Construct one schema record with immutable source metadata.
Parameters:
-
values(dict[str, Any]) –Parsed field values keyed by schema attribute name.
-
cells(Mapping[str, TableCell]) –Source cells keyed by schema attribute name.
-
row(int | None, default:None) –Source row for row-oriented records.
-
column(int | None, default:None) –Source ID column for column-oriented records.
-
item_id(Any | None, default:None) –Parsed record ID when available.
-
extras(Mapping[str, Any] | None, default:None) –Preserved inapplicable variant values.
Returns:
-
BaseTable–Populated schema record.
Info
Source metadata is attached before validation hooks run so custom validators can raise source-aware diagnostics.
_finalize_records
classmethod
⚓︎
_finalize_records(
records: list[BaseTable],
parse_context: ParseContext,
errors: DiagnosticCollector,
*,
convert_output: bool = True,
output_model: Callable[..., Any] | None = None,
) -> list[Any]
Run reference resolution, validation, and output conversion.
Parameters:
-
records(list[BaseTable]) –Parsed schema records.
-
parse_context(ParseContext) –Parse context for the current operation.
-
errors(DiagnosticCollector) –Lifecycle diagnostic collector.
-
convert_output(bool, default:True) –Whether to call output builders.
-
output_model(Callable[..., Any] | None, default:None) –Explicit callable applied to every converted record.
Returns:
Raises:
-
TableError–In fail-fast mode for reference, validation, or output failures.
-
TableErrors–In collect mode when diagnostics were collected.
Warning
Dependent lifecycle stages run only after structural parse errors have been raised. This keeps collected diagnostics actionable.
ColumnTable
⚓︎
Bases: BaseTable
Parse tables whose first column contains labels and later columns are records.
Example
parse
classmethod
⚓︎
parse(
datatable: RawTable | TableData,
*,
context: Mapping[str, Any] | ParseContext | None = None,
error_mode: str = "first",
) -> list[TableT]
Parse a column-oriented table into validated schema records.
Parameters:
-
datatable(RawTable | TableData) –Raw rows or source-aware
TableData. -
context(Mapping[str, Any] | ParseContext | None, default:None) –Optional project data or existing parse context.
-
error_mode(str, default:'first') –"first"or"collect".
Returns:
-
list[TableT]–Validated instances of this column schema. Configured output models
-
list[TableT]–and builders are intentionally not called.
Raises:
-
ValueError–If
error_modeis unsupported. -
SchemaDefinitionError–If the schema family is invalid.
-
TableError–If the first error-severity failure is found.
-
TableErrors–If collect mode finds one or more error-severity failures.
Info
The first column supplies labels. Each following column is parsed as one record.
Note
Warning-severity validation diagnostics are emitted as
TalikaWarning and do not discard the records.
parse_as
classmethod
⚓︎
parse_as(
datatable: RawTable | TableData,
output_model: Callable[..., OutputT] | None = None,
*,
context: Mapping[str, Any] | ParseContext | None = None,
error_mode: str = "first",
) -> list[OutputT] | list[Any]
Parse column records and convert them into public output objects.
Parameters:
-
datatable(RawTable | TableData) –Raw rows or source-aware
TableData. -
output_model(Callable[..., OutputT] | None, default:None) –Optional callable receiving every parsed field as a keyword argument. When omitted, each record uses its configured
output_modelor custombuild_output()hook. -
context(Mapping[str, Any] | ParseContext | None, default:None) –Optional project data or existing parse context.
-
error_mode(str, default:'first') –"first"or"collect".
Returns:
-
list[OutputT] | list[Any]–Objects created after parsing, references, and validation finish.
-
list[OutputT] | list[Any]–Supplying a callable produces
list[OutputT].
Raises:
-
TypeError–If
output_modelis not callable. -
ValueError–If no explicit or configured conversion exists.
-
TableError–If parsing, validation, or output construction fails.
-
TableErrors–If collect mode finds multiple failures.
Info
An explicit callable overrides configured base and variant output hooks for this call.
Note
Warning-severity validation diagnostics are emitted as
TalikaWarning before converted objects are returned.
validate
classmethod
⚓︎
validate(
datatable: RawTable | TableData,
*,
context: Mapping[str, Any] | ParseContext | None = None,
) -> ValidationResult[TableT]
Validate a column table without raising table-data diagnostics.
Output models and custom output builders are deliberately skipped. Invalid results contain no partial records.
Parameters:
-
datatable(RawTable | TableData) –Raw rows or source-aware
TableData. -
context(Mapping[str, Any] | ParseContext | None, default:None) –Optional project data or existing parse context.
Returns:
-
ValidationResult[TableT]–Complete schema records and ordered diagnostics. Warning-only
-
ValidationResult[TableT]–results are valid and retain their records.
Raises:
-
SchemaDefinitionError–If the schema family is invalid.
RowTable
⚓︎
Bases: BaseTable
Parse tables whose first row contains labels and later rows are records.
Example
parse
classmethod
⚓︎
parse(
datatable: RawTable | TableData,
*,
context: Mapping[str, Any] | ParseContext | None = None,
error_mode: str = "first",
) -> list[TableT]
Parse a row-oriented table into validated schema records.
Parameters:
-
datatable(RawTable | TableData) –Raw rows or source-aware
TableData. -
context(Mapping[str, Any] | ParseContext | None, default:None) –Optional project data or existing parse context.
-
error_mode(str, default:'first') –"first"or"collect".
Returns:
-
list[TableT]–Validated instances of this row schema. Configured output models
-
list[TableT]–and builders are intentionally not called.
Raises:
-
ValueError–If
error_modeis unsupported. -
SchemaDefinitionError–If the schema family is invalid.
-
TableError–If the first error-severity failure is found.
-
TableErrors–If collect mode finds one or more error-severity failures.
Info
The first row supplies labels. Each following row is parsed as one record using those labels.
Note
Warning-severity validation diagnostics are emitted as
TalikaWarning and do not discard the records.
parse_as
classmethod
⚓︎
parse_as(
datatable: RawTable | TableData,
output_model: Callable[..., OutputT] | None = None,
*,
context: Mapping[str, Any] | ParseContext | None = None,
error_mode: str = "first",
) -> list[OutputT] | list[Any]
Parse row records and convert them into public output objects.
Parameters:
-
datatable(RawTable | TableData) –Raw rows or source-aware
TableData. -
output_model(Callable[..., OutputT] | None, default:None) –Optional callable receiving every parsed field as a keyword argument. When omitted, each record uses its configured
output_modelor custombuild_output()hook. -
context(Mapping[str, Any] | ParseContext | None, default:None) –Optional project data or existing parse context.
-
error_mode(str, default:'first') –"first"or"collect".
Returns:
-
list[OutputT] | list[Any]–Objects created after parsing, references, and validation finish.
-
list[OutputT] | list[Any]–Supplying a callable produces
list[OutputT].
Raises:
-
TypeError–If
output_modelis not callable. -
ValueError–If no explicit or configured conversion exists.
-
TableError–If parsing, validation, or output construction fails.
-
TableErrors–If collect mode finds multiple failures.
Info
An explicit callable overrides configured base and variant output hooks for this call.
Note
Warning-severity validation diagnostics are emitted as
TalikaWarning before converted objects are returned.
validate
classmethod
⚓︎
validate(
datatable: RawTable | TableData,
*,
context: Mapping[str, Any] | ParseContext | None = None,
) -> ValidationResult[TableT]
Validate a row table without raising table-data diagnostics.
Output models and custom output builders are deliberately skipped. Invalid results contain no partial records.
Parameters:
-
datatable(RawTable | TableData) –Raw rows or source-aware
TableData. -
context(Mapping[str, Any] | ParseContext | None, default:None) –Optional project data or existing parse context.
Returns:
-
ValidationResult[TableT]–Complete schema records and ordered diagnostics. Warning-only
-
ValidationResult[TableT]–results are valid and retain their records.
Raises:
-
SchemaDefinitionError–If the schema family is invalid.
SchemaMeta
⚓︎
Bases: type
Collect field declarations and validate schema classes as they form.
Info
Schema creation is where inheritance, annotation-driven parser inference, and declarative variant generation become concrete runtime metadata.
__new__
⚓︎
Create one schema class.
Parameters:
-
name(str) –Class name being created.
-
bases(tuple[type, ...]) –Base classes from the class definition.
-
namespace(dict[str, Any]) –Class body namespace.
Returns:
-
SchemaMeta–Created schema class.
Raises:
-
TypeError–If declarative variant configuration is invalid.
-
SchemaDefinitionError–If labels or policies are ambiguous.
Info
Inherited fields are cloned before being attached to the new class. This prevents parser inference or descriptor naming on a subclass from mutating the base schema declaration.
__setattr__
⚓︎
Reject mutation of metadata consumed by a compiled schema plan.
_register_component_variants
⚓︎
_register_component_variants(declared: Field) -> None
Compose declarative variant components with their table schema.
Parameters:
-
cls(Any) –Base table schema declaring
discriminator(..., variants=...). -
declared(Field) –Discriminator field containing the component mapping.
Raises:
-
TypeError–If a mapping value is not a
TableFieldscomponent.
Info
Generated variant classes inherit from both the component and the base schema, so selected records are instances of the base table and the active component.
TableFields
⚓︎
Base class for reusable groups of field declarations.
Components do not parse tables by themselves. Mix them into a concrete
schema after RowTable or ColumnTable so their fields are collected
by the shared schema metaclass.