Skip to content

Package API⚓︎

talika ⚓︎

Public API for talika.

The package exports the schema, parser, transformation, context, diagnostic, introspection, pytest, and CLI-checking helpers intended for normal project use. Top-level exports include both everyday helpers and advanced extension objects so projects can build custom parsers, transformers, and diagnostics without depending on private module paths.

Info

Install optional extras only for integrations you use. Core schema parsing has no runtime dependencies beyond the Python standard library.

FeatureDiagnostic dataclass ⚓︎

FeatureDiagnostic(
    path: Path, feature: str, scenario: str, step: str, error: TableError
)

One schema diagnostic associated with a feature file and step.

Attributes:

  • path (Path) –

    Feature file path.

  • feature (str) –

    Feature name.

  • scenario (str) –

    Scenario or background name.

  • step (str) –

    Step text that owns the failing data table.

  • error (TableError) –

    Structured table error raised by schema parsing.

Info

CLI JSON output is a rendering of this object plus the nested TableError attributes.

diagnostic property ⚓︎

diagnostic: Diagnostic

Return the shared immutable Diagnostic Model v1 value.

FeatureTable dataclass ⚓︎

FeatureTable(path: Path, feature: str, scenario: str, step: str, table: TableData)

One discovered Gherkin step data table.

Attributes:

  • path (Path) –

    Feature file path.

  • feature (str) –

    Feature name.

  • scenario (str) –

    Scenario or background name.

  • step (str) –

    Step text that owns the data table.

  • table (TableData) –

    Source-aware table converted from Gherkin AST cells.

Info

The stored TableData uses feature-file line and column coordinates, not indexes relative to the data table block.

CellContext dataclass ⚓︎

CellContext(
    schema: type,
    field_name: str,
    field_label: str,
    row: int | None,
    column: int | None,
    item_id: Any | None,
    source_value: str,
    user_data: Mapping[str, Any],
    source_uri: str | None = None,
)

Source location and project data supplied to a field parser.

value is passed separately to a field parser and represents the current, possibly transformed value. source_value records what was written in the original Gherkin data table before table transformation.

Attributes:

  • schema (type) –

    Concrete schema class parsing the cell.

  • field_name (str) –

    Python attribute name receiving the parsed value.

  • field_label (str) –

    Canonical Gherkin data table label for the field.

  • row (int | None) –

    One-based source row when available.

  • column (int | None) –

    One-based source column when available.

  • item_id (Any | None) –

    Parsed record ID when available.

  • source_value (str) –

    Original feature-file text before transformation.

  • user_data (Mapping[str, Any]) –

    Read-only project data from ParseContext.

  • source_uri (str | None) –

    URI of the source document when known.

Warning

Parser functions receive the current value as a separate argument. Use source_value only when diagnostics or project syntax need the original feature text.

DefaultContext dataclass ⚓︎

DefaultContext(
    schema: type,
    field_name: str,
    field_label: str,
    item_id: Any | None,
    user_data: Mapping[str, Any],
    source_uri: str | None = None,
)

Context supplied when a missing optional field uses a factory.

Default factories do not have a source cell because the field was omitted from the Gherkin data table. They still receive the selected schema, field identity, item ID when available, and the same read-only project data supplied to the parse operation.

Attributes:

  • schema (type) –

    Concrete schema class building the default.

  • field_name (str) –

    Python attribute name receiving the default.

  • field_label (str) –

    Canonical Gherkin data table label for the field.

  • item_id (Any | None) –

    Parsed record ID when available.

  • user_data (Mapping[str, Any]) –

    Read-only project data from ParseContext.

  • source_uri (str | None) –

    URI of the source document when known.

Info

Default factories run only for missing optional fields, not for explicit empty cells.

ParseContext dataclass ⚓︎

ParseContext(user_data: Mapping[str, Any] = (lambda: MappingProxyType({}))())

Project-owned dependencies and settings for one parse operation.

The library copies the supplied mapping and exposes it as read-only user_data. Cell parsers, table transformers, and record validators all receive data originating from this same context object.

Attributes:

  • user_data (Mapping[str, Any]) –

    Read-only mapping of project-owned dependencies and settings.

Example

UserTable.parse(datatable, context={"faker": faker})

from_value classmethod ⚓︎

from_value(value: Mapping[str, Any] | ParseContext | None) -> ParseContext

Normalize raw context input.

Parameters:

Returns:

  • ParseContext

    A ParseContext instance with read-only user_data.

Raises:

  • TypeError

    If value cannot be copied as a mapping.

Info

Existing ParseContext objects pass through unchanged, which lets advanced callers construct and reuse immutable context values.

Diagnostic dataclass ⚓︎

Diagnostic(
    *,
    code: str,
    message: str,
    severity: DiagnosticSeverity | str = ERROR,
    hint: str | None = None,
    schema_name: str | None = None,
    field_name: str | None = None,
    field_label: str | None = None,
    source_uri: str | None = None,
    row: int | None = None,
    column: int | None = None,
    item_id: Any = _UNSET,
    source_value: Any = _UNSET,
    logical_value: Any = _UNSET,
    cause: BaseException | None = None,
)

One immutable, source-aware Diagnostic Model v1 value.

item_id property ⚓︎

item_id: Any | None

Return the item ID, or None when it was omitted.

has_item_id property ⚓︎

has_item_id: bool

Return whether the diagnostic explicitly carries an item ID.

source_value property ⚓︎

source_value: Any | None

Return the original source value, or None when omitted.

has_source_value property ⚓︎

has_source_value: bool

Return whether an original source value is present.

logical_value property ⚓︎

logical_value: Any | None

Return the logical/transformed value, or None when omitted.

has_logical_value property ⚓︎

has_logical_value: bool

Return whether a logical/transformed value is present.

as_dict ⚓︎

as_dict() -> dict[str, Any]

Return a deterministic JSON-compatible Diagnostic Model v1 mapping.

DiagnosticSeverity ⚓︎

Bases: str, Enum

Severity values supported by Diagnostic Model v1.

TalikaWarning ⚓︎

TalikaWarning(diagnostic: Diagnostic)

Bases: UserWarning

Expose one structured Talika diagnostic through Python warnings.

Raising parse APIs return their normal records or output models when validation reports warning-severity diagnostics. Each diagnostic is also emitted as TalikaWarning so callers may display, filter, or assert it with the standard :mod:warnings tools.

Attributes:

  • diagnostic

    Immutable warning-severity diagnostic produced by Talika.

Parameters:

  • diagnostic (Diagnostic) –

    Structured diagnostic to expose as a Python warning.

Raises:

  • ValueError

    If the diagnostic does not have warning severity.

Example

with pytest.warns(TalikaWarning) as captured:
    records = UserTable.parse(datatable)

assert captured[0].message.diagnostic.code == "legacy_value"

ValidationResult dataclass ⚓︎

ValidationResult(
    records: tuple[T, ...] = (), diagnostics: tuple[Diagnostic, ...] = ()
)

Bases: Generic[T]

Non-raising result returned by Schema.validate().

errors property ⚓︎

errors: tuple[Diagnostic, ...]

Return error-severity diagnostics in discovery order.

warnings property ⚓︎

warnings: tuple[Diagnostic, ...]

Return warning-severity diagnostics in discovery order.

valid property ⚓︎

valid: bool

Return whether validation found no error-severity diagnostics.

CellDSL ⚓︎

CellDSL()

Dispatch cell values to project-defined parsing handlers.

Dispatch order is exact tokens, regular-expression patterns, predicates, and finally the optional fallback. For an exact token, field-scoped rules take precedence over a global rule with the same value. Pattern and predicate rules otherwise retain registration order.

Example

content_cells = CellDSL()

@content_cells.token("random", fields=("headline",))
def random_headline(context):
    return context.user_data["faker"].headline()

Initialize an empty rule registry.

Info

Registration mutates only this DSL instance. Once the instance is attached to a schema field, parsing uses the rules accumulated on that object.

token ⚓︎

token(
    value: str, *, fields: Iterable[str] | None = None
) -> Callable[[TokenHandler], TokenHandler]

Register an exact token.

Parameters:

  • value (str) –

    Exact cell text that should trigger the decorated handler.

  • fields (Iterable[str] | None, default: None ) –

    Optional schema attribute name or names that limit where the token applies.

Returns:

  • Callable[[TokenHandler], TokenHandler]

    A decorator that stores and returns the project handler unchanged.

Raises:

  • ValueError

    If value is empty or the same token/scope pair is registered twice.

Warning

Field-scoped tokens use schema attribute names. A field declared as headline = field("Headline*") is scoped as "headline", not "Headline*".

pattern ⚓︎

pattern(
    expression: str, *, fields: Iterable[str] | None = None
) -> Callable[[PatternHandler], PatternHandler]

Register a full-match regular expression.

Parameters:

  • expression (str) –

    Regular-expression text compiled immediately.

  • fields (Iterable[str] | None, default: None ) –

    Optional schema attribute name or names that limit where the pattern applies.

Returns:

  • Callable[[PatternHandler], PatternHandler]

    A decorator that stores and returns the project handler unchanged.

Raises:

  • ValueError

    If the same expression/scope pair is registered twice.

  • error

    If expression is not a valid regular expression.

Info

Pattern handlers receive the re.Match object so capture groups can become typed values without reparsing the cell text.

when ⚓︎

when(
    predicate: Predicate, *, fields: Iterable[str] | None = None
) -> Callable[[PredicateHandler], PredicateHandler]

Register a project predicate for syntax awkward to express as regex.

Predicates run after exact tokens and regular expressions. They should return a boolean and avoid side effects because only the handler's return value becomes the parsed cell value.

Parameters:

  • predicate (Predicate) –

    Callable that decides whether a value should match.

  • fields (Iterable[str] | None, default: None ) –

    Optional schema attribute name or names that limit where the predicate applies.

Returns:

  • Callable[[PredicateHandler], PredicateHandler]

    A decorator that stores and returns the predicate handler.

Warning

Predicates are tried in registration order after token and pattern rules. Keep them cheap and deterministic.

fallback ⚓︎

fallback(handler: FallbackHandler) -> FallbackHandler

Register behavior for values that match no explicit rule.

Parameters:

  • handler (FallbackHandler) –

    Project callable receiving the raw value and context.

Returns:

  • FallbackHandler

    The same handler supplied by the caller.

Raises:

  • ValueError

    If a fallback is already registered.

Warning

A fallback makes the DSL match every value, which also affects CellDSLChain composition. Use it only when the DSL should own unmatched values.

compose ⚓︎

compose(*others: CellDSL) -> CellDSLChain

Return a first-match chain beginning with this DSL.

Parameters:

  • *others (CellDSL, default: () ) –

    Additional DSLs consulted after this one.

Returns:

Example

parser = shared_cells.compose(project_cells)
value = parser("random", context)

_dispatch ⚓︎

_dispatch(value: str, context: CellContext) -> tuple[bool, Any]

Return (matched, result) for composition-aware dispatch.

Parameters:

  • value (str) –

    Current logical cell value.

  • context (CellContext) –

    Parser context for the active schema field.

Returns:

  • bool

    (True, parsed_value) when a rule or fallback handles the value,

  • Any

    otherwise (False, value).

Info

CellDSLChain uses the matched flag to distinguish "a DSL intentionally returned the original text" from "this DSL did not match".

__call__ ⚓︎

__call__(value: str, context: CellContext) -> Any

Parse one value or pass it through when no rule matches.

Parameters:

  • value (str) –

    Current logical cell value.

  • context (CellContext) –

    Parser context for the active schema field.

Returns:

  • Any

    The parsed value from the first matching rule, fallback result, or

  • Any

    original text when no rule applies.

Info

This method satisfies the same callable contract as ordinary field parsers, so a CellDSL instance can be passed directly to field(parser=...).

CellDSLChain ⚓︎

CellDSLChain(dsls: Sequence[CellDSL])

Ask several CellDSL objects in first-match order.

Attributes:

  • dsls

    Immutable ordered DSL sequence consulted during parsing.

Info

Chains are useful when a project has shared tokens plus feature-area specific rules. The first DSL that reports a match owns the result.

Validate and store composed DSLs.

Parameters:

Raises:

Warning

A DSL with a fallback always matches, so later DSLs in the chain will never see values that reach it.

__call__ ⚓︎

__call__(value: str, context: CellContext) -> Any

Return the first result from the composed DSLs.

Parameters:

  • value (str) –

    Current logical cell value.

  • context (CellContext) –

    Parser context for the active schema field.

Returns:

  • Any

    Parsed value from the first matching DSL, or the original text when

  • Any

    none match.

Info

The original value can still be a deliberate parsed result when a DSL matches and returns it; the chain preserves that distinction.

SchemaDefinitionError ⚓︎

SchemaDefinitionError(message: str, *, schema: str | None = None)

Bases: ValueError

Report an invalid schema declaration before table input is parsed.

Attributes:

  • message

    Human-readable declaration problem.

  • schema

    Name of the schema being created when available.

Warning

These errors normally occur during class creation. Explicit variant families may be completed by decorators, so their family-wide checks run when the family is described or first finalized for parsing.

Initialize a schema-definition failure.

Parameters:

  • message (str) –

    Human-readable declaration problem.

  • schema (str | None, default: None ) –

    Optional schema name associated with the problem.

Info

The formatted exception includes the schema name because these failures often occur during import before any table is parsed.

TableError ⚓︎

TableError(
    message: str,
    *,
    schema: type | str | None = None,
    field: str | None = None,
    field_name: str | None = None,
    field_label: str | None = None,
    source_uri: str | None = None,
    row: int | None = None,
    column: int | None = None,
    item_id: Any = _UNSET,
    value: Any = _UNSET,
    source_value: Any = _UNSET,
    logical_value: Any = _UNSET,
    code: TableErrorCode | str = TABLE_ERROR,
    hint: str | None = None,
    severity: DiagnosticSeverity | str = ERROR,
    cause: BaseException | None = None,
)

Bases: ValueError

Represent one source-aware table diagnostic.

The structured attributes are intentionally public. Test runners and editor integrations can inspect them without parsing the human-readable error message.

Attributes:

  • message (str) –

    Human-readable failure summary.

  • schema (str | None) –

    Schema display name when known.

  • field (str | None) –

    Legacy human-facing field label associated with the failure.

  • field_name (str | None) –

    Python attribute name associated with the failure.

  • field_label (str | None) –

    Authored field label associated with the failure.

  • source_uri (str | None) –

    URI of the source document when known.

  • row (int | None) –

    One-based source row.

  • column (int | None) –

    One-based source column.

  • item_id (Any | None) –

    Parsed item ID when the failing record has one.

  • value (Any | None) –

    Legacy alias for the offending source value.

  • code (str) –

    Stable machine-readable diagnostic code.

  • hint (str | None) –

    Optional remediation text.

Info

TableError inherits ValueError so project validators can raise ordinary value errors while the schema lifecycle wraps them in a table-aware diagnostic.

Initialize one structured table diagnostic.

Parameters:

  • message (str) –

    Human-readable failure summary.

  • schema (type | str | None, default: None ) –

    Schema class or display name associated with the failure.

  • field (str | None, default: None ) –

    Legacy human-facing field label.

  • field_name (str | None, default: None ) –

    Python attribute name for the declared field.

  • field_label (str | None, default: None ) –

    Authored canonical or alias label for the field.

  • source_uri (str | None, default: None ) –

    URI of the source document when known.

  • row (int | None, default: None ) –

    One-based source row.

  • column (int | None, default: None ) –

    One-based source column.

  • item_id (Any, default: _UNSET ) –

    Parsed item identifier when available.

  • value (Any, default: _UNSET ) –

    Offending source value. Omit to represent "no value".

  • source_value (Any, default: _UNSET ) –

    Original authored value, superseding value.

  • logical_value (Any, default: _UNSET ) –

    Current value after table transformation.

  • code (TableErrorCode | str, default: TABLE_ERROR ) –

    Stable diagnostic category.

  • hint (str | None, default: None ) –

    Optional user-facing remediation.

  • severity (DiagnosticSeverity | str, default: ERROR ) –

    Diagnostic severity.

  • cause (BaseException | None, default: None ) –

    Original exception when this error wraps another failure.

Warning

Passing value=None means the offending value is explicitly None. Omit value entirely when no value should be reported.

message property ⚓︎

message: str

Return the human-readable failure message.

schema property ⚓︎

schema: str | None

Return the schema display name when known.

field property ⚓︎

field: str | None

Return the legacy human-facing field identifier.

field_name property ⚓︎

field_name: str | None

Return the declared Python field name when known.

field_label property ⚓︎

field_label: str | None

Return the authored field label when known.

source_uri property ⚓︎

source_uri: str | None

Return the source document URI when known.

row property ⚓︎

row: int | None

Return the one-based source row when known.

column property ⚓︎

column: int | None

Return the one-based source column when known.

item_id property ⚓︎

item_id: Any | None

Return the parsed item identifier when present.

has_item_id property ⚓︎

has_item_id: bool

Return whether an item identifier is present.

value property ⚓︎

value: Any | None

Return the legacy alias for the original source value.

source_value property ⚓︎

source_value: Any | None

Return the original authored value when present.

logical_value property ⚓︎

logical_value: Any | None

Return the current transformed value when present.

code property ⚓︎

code: str

Return the stable machine-readable diagnostic code.

hint property ⚓︎

hint: str | None

Return optional remediation text.

severity property ⚓︎

Return the diagnostic severity.

has_value property ⚓︎

has_value: bool

Return whether the diagnostic contains an offending value.

Returns:

  • bool

    True when value was supplied to the error constructor.

Info

This distinguishes an omitted value from an explicit None.

from_diagnostic classmethod ⚓︎

from_diagnostic(diagnostic: Diagnostic) -> TableError

Create a compatibility exception around an existing diagnostic.

from_cell classmethod ⚓︎

from_cell(
    message: str,
    cell: TableCell,
    *,
    schema: type | str | None = None,
    field: str | None = None,
    field_name: str | None = None,
    field_label: str | None = None,
    source_uri: str | None = None,
    item_id: Any = _UNSET,
    code: TableErrorCode | str = TABLE_ERROR,
    hint: str | None = None,
    severity: DiagnosticSeverity | str = ERROR,
    cause: BaseException | None = None,
) -> TableError

Create an error located at a cell's original source.

This helper is useful inside custom table transformations. It reports the source syntax, not merely the current transformed value.

Parameters:

  • message (str) –

    Human-readable failure summary.

  • cell (TableCell) –

    Source-aware cell that caused the error.

  • schema (type | str | None, default: None ) –

    Schema class or display name associated with the failure.

  • field (str | None, default: None ) –

    Legacy human-facing field label.

  • field_name (str | None, default: None ) –

    Python attribute name for the declared field.

  • field_label (str | None, default: None ) –

    Authored canonical or alias label for the field.

  • source_uri (str | None, default: None ) –

    Source document URI, overriding the cell URI.

  • item_id (Any, default: _UNSET ) –

    Parsed item identifier when available.

  • code (TableErrorCode | str, default: TABLE_ERROR ) –

    Stable diagnostic category.

  • hint (str | None, default: None ) –

    Optional user-facing remediation.

  • severity (DiagnosticSeverity | str, default: ERROR ) –

    Diagnostic severity.

  • cause (BaseException | None, default: None ) –

    Original exception when this error wraps another failure.

Returns:

  • TableError

    A TableError populated from cell source coordinates.

Example

raise TableError.from_cell(
    "Invalid compact range",
    source_cell,
    schema=ContentTable,
)

__str__ ⚓︎

__str__() -> str

Return a compact message with structured context appended.

Returns:

  • str

    The human-facing diagnostic text used by ValueError and CLI

  • str

    text output.

Info

The string is intentionally readable, but integrations should prefer attributes such as code, row, and field.

TableErrorCode ⚓︎

Bases: str, Enum

Stable machine-readable categories for table failures.

Human-readable messages may improve over time. Integrations should use these codes when grouping diagnostics or deciding how to present them.

Warning

Codes are part of the supported diagnostic contract. Prefer adding new codes over changing existing meanings.

TableErrors ⚓︎

TableErrors(errors: list[TableError] | tuple[TableError, ...])

Bases: ValueError

Aggregate raised when collect mode finds several table failures.

The contained errors retain their normal structured attributes and source locations. The aggregate itself is intentionally small so test runners, editor extensions, and command-line tools can render diagnostics in the format most useful to their users.

Attributes:

  • errors

    Immutable tuple of collected TableError objects.

Info

Collection preserves discovery order so rendered diagnostics follow the table as closely as possible.

Initialize an aggregate of one or more diagnostics.

Parameters:

Raises:

Warning

Empty aggregates are rejected because their string representation would imply a failure without any actionable diagnostic.

diagnostics property ⚓︎

diagnostics: tuple[Diagnostic, ...]

Return underlying immutable diagnostics in discovery order.

__iter__ ⚓︎

__iter__() -> Iterator[TableError]

Iterate over diagnostics in discovery order.

Returns:

Info

This lets callers use list(exc) or simple loops without reaching into exc.errors directly.

__len__ ⚓︎

__len__() -> int

Return the number of collected diagnostics.

Returns:

  • int

    Count of contained TableError objects.

Info

len(exc) mirrors the number reported in the aggregate message.

__str__ ⚓︎

__str__() -> str

Return a numbered multi-line diagnostic summary.

Returns:

  • str

    Human-readable text containing every collected error.

Info

The aggregate string is convenient for test failures; structured renderers should iterate over errors instead.

Field dataclass ⚓︎

Field(
    label: str | None,
    aliases: tuple[str, ...] = (),
    required: bool = False,
    default: Any = MISSING,
    default_factory: DefaultFactory | object = MISSING,
    parser: Parser | None = None,
    empty: str = "raw",
    is_id: bool = False,
    is_discriminator: bool = False,
    variants: Mapping[Any, type] | None = None,
    reference: ReferenceSpec | None = None,
    name: str = "",
)

Store one declared schema field and its conversion behavior.

Attributes:

  • label (str | None) –

    Canonical Gherkin data table label. None is accepted only while an ordinary field() waits for its Python attribute name.

  • aliases (tuple[str, ...]) –

    Alternate accepted labels for evolving feature vocabulary.

  • required (bool) –

    Whether the field must be present and non-empty.

  • default (Any) –

    Static value used when an optional field is absent.

  • default_factory (DefaultFactory | object) –

    Context-aware factory used when an optional field is absent.

  • parser (Parser | None) –

    Optional callable used to convert non-empty cell values.

  • empty (str) –

    Effective policy for explicit empty cells.

  • is_id (bool) –

    Whether this field identifies column-oriented records.

  • is_discriminator (bool) –

    Whether this field selects record variants.

  • variants (Mapping[Any, type] | None) –

    Declarative discriminator component mapping.

  • reference (ReferenceSpec | None) –

    Optional local-record reference configuration.

  • name (str) –

    Python attribute name assigned by the schema class body.

Warning

Field instances are mutable during class creation because __set_name__ records their Python attribute name. Schema inheritance uses clone() to avoid sharing that mutable state. The declaration is frozen after its schema plan is compiled.

labels property ⚓︎

labels: tuple[str, ...]

Return the canonical label followed by accepted aliases.

Returns:

  • tuple[str, ...]

    Tuple used during label matching and duplicate-label validation.

Info

Canonical label order is preserved so introspection can present the preferred table vocabulary first.

__setattr__ ⚓︎

__setattr__(name: str, value: Any) -> None

Set declaration metadata while the field is being compiled.

Compiled declarations are immutable. Parsed record assignment still uses :meth:__set__ and is deliberately unaffected by this guard.

clone ⚓︎

clone() -> Field

Return an independent declaration for schema inheritance.

Returns:

  • Field

    A new Field with the same declaration options.

Info

Schema subclasses receive cloned fields so changing an inferred parser or descriptor name on one schema does not mutate its base schema's declaration.

__set_name__ ⚓︎

__set_name__(owner: type, name: str) -> None

Record the Python attribute name assigned by a schema class.

Parameters:

  • owner (type) –

    Schema class receiving the descriptor.

  • name (str) –

    Attribute name used in the class body.

Info

The table label and the Python attribute name are intentionally separate so feature files can use human-facing language while code keeps normal Python identifiers.

_freeze ⚓︎

_freeze() -> None

Freeze declaration metadata after schema compilation.

__get__ ⚓︎

__get__(instance: object | None, owner: type | None = None) -> Any

Return the declaration on classes or parsed value on records.

Parameters:

  • instance (object | None) –

    Parsed record instance, or None during class access.

  • owner (type | None, default: None ) –

    Owning schema class.

Returns:

  • Any

    The Field declaration when accessed on a class, otherwise the

  • Any

    parsed attribute value stored on the record.

Warning

Parsed records are created through the schema lifecycle. Accessing a descriptor-backed attribute before construction populates the instance dictionary will raise KeyError.

__set__ ⚓︎

__set__(instance: object, value: Any) -> None

Store a parsed value on a record instance.

Parameters:

  • instance (object) –

    Parsed record object being populated.

  • value (Any) –

    Parsed field value.

Info

Assignment is intentionally direct. Validation and conversion have already happened before values are attached to records.

ReferenceSpec dataclass ⚓︎

ReferenceSpec(target: str, many: bool, separator: str)

Configure local ID resolution within the same parsed table.

Attributes:

  • target (str) –

    Attribute name on the referenced record used as the lookup key.

  • many (bool) –

    Whether the source cell contains several references.

  • separator (str) –

    Text separator used when many is true.

Info

Reference resolution happens after records are constructed and before record/table validation hooks run.

AlphabeticRange dataclass ⚓︎

AlphabeticRange(separator: str = '-')

Expand inclusive ASCII letter ranges such as A-D or a-d.

Endpoints must each be one ASCII letter and use the same case. Values without the configured separator remain literal keys.

Attributes:

  • separator (str) –

    Text separating the inclusive start and end letters.

Warning

Only single ASCII letters are supported. Use a custom range rule for multi-character labels, Unicode collation, or domain-specific IDs.

__post_init__ ⚓︎

__post_init__() -> None

Validate the configured separator after dataclass initialization.

Raises:

Info

Keeping this check on the rule object makes custom expander failures easier to diagnose.

expand ⚓︎

expand(cell: TableCell, context: ParseContext) -> list[TableCell]

Return one literal key or an inclusive letter-key sequence.

Parameters:

  • cell (TableCell) –

    Key cell to inspect for alphabetic range syntax.

  • context (ParseContext) –

    Parse context for the current schema parse.

Returns:

  • list[TableCell]

    [cell] for literal values, or generated cells for each ASCII

  • list[TableCell]

    letter in the inclusive range.

Raises:

  • ValueError

    If recognized range syntax is malformed or descending.

Info

Case must match between endpoints so A-D and a-d are clear, while A-d is rejected.

ColumnGroupExpander dataclass ⚓︎

ColumnGroupExpander(key_row: str, range_rule: RangeRule, repeat_rule: RepeatRule)

Expand grouped columns using replaceable range and repeat rules.

Parameters:

  • key_row (str) –

    Literal label expected in the first cell of the first row.

  • range_rule (RangeRule) –

    Object implementing :class:RangeRule.

  • repeat_rule (RepeatRule) –

    Object implementing :class:RepeatRule.

The expander owns the repetitive table mechanics: rectangular-shape checks, group iteration, source preservation, count validation, and TableData construction. Rule objects own syntax recognition and value expansion.

Example

table_transformer = ColumnGroupExpander(
    key_row="IDs",
    range_rule=NumericRange(separator=".."),
    repeat_rule=PrefixRepeat(separator=":"),
)

transform ⚓︎

transform(
    table: TableData, context: ParseContext, *, schema: type | str | None = None
) -> TableData

Return an expanded logical table ready for schema parsing.

Parameters:

  • table (TableData) –

    Source-aware grouped table.

  • context (ParseContext) –

    Parse context for the current schema parse.

  • schema (type | str | None, default: None ) –

    Optional schema identity used in diagnostics.

Returns:

  • TableData

    A rectangular TableData where grouped columns have been

  • TableData

    expanded into one logical record column per key.

Raises:

  • TableError

    If the table is empty, non-rectangular, has the wrong key row, or a custom rule returns invalid cells.

Warning

This transformer expects a column-oriented grouped shape. Use a custom transform_table() override for unrelated compact table conventions.

_expand_range ⚓︎

_expand_range(
    cell: TableCell, context: ParseContext, schema: type | str | None
) -> list[TableCell]

Run a range rule and normalize its errors.

Parameters:

  • cell (TableCell) –

    Source key cell to expand.

  • context (ParseContext) –

    Parse context for the current schema parse.

  • schema (type | str | None) –

    Optional schema identity used in diagnostics.

Returns:

  • list[TableCell]

    A list of TableCell objects produced by the range rule.

Raises:

  • TableError

    If the rule raises a table error, raises another exception, or returns non-cell values.

Info

Custom ValueError failures are wrapped with source-cell coordinates so feature authors see the compact key cell.

_expand_repeat ⚓︎

_expand_repeat(
    cell: TableCell,
    expected_count: int,
    context: ParseContext,
    schema: type | str | None,
) -> list[TableCell]

Run a repeat rule and normalize its errors.

Parameters:

  • cell (TableCell) –

    Source value cell to expand.

  • expected_count (int) –

    Number of logical cells required.

  • context (ParseContext) –

    Parse context for the current schema parse.

  • schema (type | str | None) –

    Optional schema identity used in diagnostics.

Returns:

  • list[TableCell]

    A list of TableCell objects produced by the repeat rule.

Raises:

  • TableError

    If the rule raises a table error, raises another exception, or returns non-cell values.

Warning

This method validates object type only. The public transform method additionally checks that the returned count matches the key group size.

_require_cells staticmethod ⚓︎

_require_cells(
    cells: Sequence[object],
    source: TableCell,
    rule_name: str,
    schema: type | str | None,
) -> None

Ensure custom rules return TableCell instances.

Parameters:

  • cells (Sequence[object]) –

    Objects returned by a range or repeat rule.

  • source (TableCell) –

    Source cell used when reporting invalid return values.

  • rule_name (str) –

    Human-readable rule family for diagnostics.

  • schema (type | str | None) –

    Optional schema identity used in diagnostics.

Raises:

  • TableError

    If any returned object is not a TableCell.

Warning

Returning raw strings would lose source coordinates. Custom rules should call source.with_value(...) for transformed cells.

NumericRange dataclass ⚓︎

NumericRange(separator: str = '..')

Expand inclusive ascending integer ranges such as 1..4.

Values without the configured separator are treated as one literal key. Once the separator is present, both endpoints must be integers and the first endpoint must not exceed the second.

Attributes:

  • separator (str) –

    Text separating the inclusive start and end values.

Example

NumericRange(separator="..").expand(cell, context)

__post_init__ ⚓︎

__post_init__() -> None

Validate the configured separator after dataclass initialization.

Raises:

Warning

Validation happens eagerly so an invalid schema fails during setup rather than during the first feature parse.

expand ⚓︎

expand(cell: TableCell, context: ParseContext) -> list[TableCell]

Return one literal key or an inclusive integer-key sequence.

Parameters:

  • cell (TableCell) –

    Key cell to inspect for range syntax.

  • context (ParseContext) –

    Parse context for the current schema parse.

Returns:

Raises:

  • ValueError

    If recognized range syntax is malformed or descending.

Info

Generated cells keep the source row, source column, and source value from cell.

PrefixRepeat dataclass ⚓︎

PrefixRepeat(separator: str = ':')

Expand count-before-value syntax such as 3:Article.

If the text before the separator is not an integer, the entire value is treated as a literal and copied across the key group. This allows normal text containing the separator, such as News: Europe, to remain valid.

Attributes:

  • separator (str) –

    Text between repeat count and repeated value.

Example

PrefixRepeat(separator=":")  # 3:Article

__post_init__ ⚓︎

__post_init__() -> None

Validate the configured separator after dataclass initialization.

Raises:

Warning

A blank separator would make prefix parsing ambiguous for every cell value.

expand ⚓︎

expand(cell: TableCell, expected_count: int, context: ParseContext) -> list[TableCell]

Repeat recognized syntax or copy a literal value across a group.

Parameters:

  • cell (TableCell) –

    Value cell aligned with a grouped key cell.

  • expected_count (int) –

    Number of logical keys in the group.

  • context (ParseContext) –

    Parse context for the current schema parse.

Returns:

  • list[TableCell]

    One logical value cell per key in the group.

Raises:

  • ValueError

    If recognized repeat syntax is empty or has the wrong count.

Info

Non-numeric prefixes are treated as literal values so ordinary text containing the separator remains usable in feature files.

RangeRule ⚓︎

Bases: Protocol

Contract for turning one key cell into one or more logical keys.

Info

Custom range rules can implement any project convention, such as numeric ranges, alphabetic ranges, or domain-specific IDs.

expand ⚓︎

expand(cell: TableCell, context: ParseContext) -> Sequence[TableCell]

Return logical key cells derived from cell.

A value that does not use the rule's special syntax should normally return [cell]. Invalid recognized syntax may raise ValueError; ColumnGroupExpander converts it into a source-aware TableError.

Parameters:

  • cell (TableCell) –

    Source key cell from the grouped table.

  • context (ParseContext) –

    Parse context for the current schema parse.

Returns:

  • Sequence[TableCell]

    One or more TableCell objects representing logical item keys.

Warning

Return TableCell objects, not raw strings. Use cell.with_value(...) so diagnostics still point to the compact source cell.

RepeatRule ⚓︎

Bases: Protocol

Contract for spreading one value cell across a logical key group.

Info

Repeat rules own value syntax only. The expander owns table shape, row iteration, count checks, and TableData construction.

expand ⚓︎

expand(
    cell: TableCell, expected_count: int, context: ParseContext
) -> Sequence[TableCell]

Return exactly expected_count logical value cells.

A value without repeat syntax should normally be copied across the group. Invalid recognized syntax may raise ValueError.

Parameters:

  • cell (TableCell) –

    Source value cell aligned with a grouped key cell.

  • expected_count (int) –

    Number of logical key cells in the group.

  • context (ParseContext) –

    Parse context for the current schema parse.

Returns:

Warning

Count mismatches are treated as table errors because they would produce ambiguous record values.

SuffixRepeat dataclass ⚓︎

SuffixRepeat(separator: str = ' x')

Expand value-before-count syntax such as Article x3.

If the text after the final separator is not an integer, the entire value is treated as a literal and copied across the key group.

Attributes:

  • separator (str) –

    Text between repeated value and repeat count.

Example

SuffixRepeat(separator=" x")  # Article x3

__post_init__ ⚓︎

__post_init__() -> None

Validate the configured separator after dataclass initialization.

Raises:

Info

Eager validation keeps invalid rule configuration close to schema import time.

expand ⚓︎

expand(cell: TableCell, expected_count: int, context: ParseContext) -> list[TableCell]

Repeat recognized syntax or copy a literal value across a group.

Parameters:

  • cell (TableCell) –

    Value cell aligned with a grouped key cell.

  • expected_count (int) –

    Number of logical keys in the group.

  • context (ParseContext) –

    Parse context for the current schema parse.

Returns:

  • list[TableCell]

    One logical value cell per key in the group.

Raises:

  • ValueError

    If recognized repeat syntax is empty or has the wrong count.

Warning

The final occurrence of separator is used. Choose separators that do not naturally appear at the end of domain values.

FieldContract dataclass ⚓︎

FieldContract(
    name: str,
    label: str,
    aliases: tuple[str, ...],
    required: bool,
    is_id: bool,
    is_discriminator: bool,
    has_default: bool,
    default_repr: str | None,
    default_factory: str | None,
    parser: str | None,
    reference_target: str | None,
    reference_many: bool,
    empty: str,
)

Public description of one declared schema field.

Attributes:

  • name (str) –

    Python schema attribute name.

  • label (str) –

    Canonical Gherkin data table label.

  • aliases (tuple[str, ...]) –

    Alternate accepted labels.

  • required (bool) –

    Whether the field is required.

  • is_id (bool) –

    Whether the field identifies column-oriented records.

  • is_discriminator (bool) –

    Whether the field selects variants.

  • has_default (bool) –

    Whether a static or factory default is configured.

  • default_repr (str | None) –

    repr of a static default when present.

  • default_factory (str | None) –

    Display name of the default factory when present.

  • parser (str | None) –

    Display name of the parser when present.

  • reference_target (str | None) –

    Referenced field name when this is a reference.

  • reference_many (bool) –

    Whether the reference contains multiple keys.

  • empty (str) –

    Explicit empty-cell policy for optional values.

Info

The contract is frozen so tools can cache it safely.

from_field classmethod ⚓︎

from_field(name: str, declared: Field) -> FieldContract

Build an immutable contract from one field declaration.

Parameters:

  • name (str) –

    Python schema attribute name.

  • declared (Field) –

    Internal Field declaration.

Returns:

  • FieldContract

    A FieldContract suitable for JSON conversion.

Warning

Defaults are represented with repr rather than copied as live objects, because contracts are descriptive metadata.

TableContract dataclass ⚓︎

TableContract(
    schema_name: str,
    orientation: str,
    fields: tuple[FieldContract, ...],
    variants: tuple[VariantContract, ...],
    unknown_fields: str,
    inapplicable_fields: str,
    transformer: str | None,
    output_model: str | None,
    output_builder: str,
)

Complete public description returned by Table.describe().

Attributes:

  • schema_name (str) –

    Display name of the described schema.

  • orientation (str) –

    "row" or "column".

  • fields (tuple[FieldContract, ...]) –

    Base schema field contracts.

  • variants (tuple[VariantContract, ...]) –

    Discriminator variant contracts.

  • unknown_fields (str) –

    Policy for undeclared table labels.

  • inapplicable_fields (str) –

    Policy for values belonging to other variants.

  • transformer (str | None) –

    Display name of configured table transformer.

  • output_model (str | None) –

    Display name of configured output model.

  • output_builder (str) –

    Display name of the output builder hook.

Example

contract = UserTable.describe()
assert contract.orientation == "row"

as_dict ⚓︎

as_dict() -> dict[str, Any]

Return a recursively structured dictionary.

Returns:

  • dict[str, Any]

    Dictionary containing only standard container values.

Info

CLI JSON output delegates to this method so editor integrations and CI scripts receive the same shape as Python callers.

VariantContract dataclass ⚓︎

VariantContract(
    value: Any,
    schema_name: str,
    fields: tuple[FieldContract, ...],
    output_model: str | None,
    output_builder: str,
)

Description of one discriminator value and selected schema.

Attributes:

  • value (Any) –

    Parsed discriminator value that selects the variant.

  • schema_name (str) –

    Display name of the concrete variant schema.

  • fields (tuple[FieldContract, ...]) –

    Field contracts active for that variant.

  • output_model (str | None) –

    Display name of the variant output model, if any.

  • output_builder (str) –

    Display name of the output builder hook.

Info

Generated variant class names may change, so tooling should present schema_name and use variant_for() for runtime lookup.

ColumnTable ⚓︎

Bases: BaseTable

Parse tables whose first column contains labels and later columns are records.

Example

class ContentTable(ColumnTable):
    id = id_field("IDs")
    headline = field("Headline*", required=True)

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:

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],
    *,
    context: Mapping[str, Any] | ParseContext | None = None,
    error_mode: str = "first",
) -> list[OutputT]
parse_as(
    datatable: RawTable | TableData,
    output_model: None = None,
    *,
    context: Mapping[str, Any] | ParseContext | None = None,
    error_mode: str = "first",
) -> list[Any]
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_model or custom build_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_model is 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:

RowTable ⚓︎

Bases: BaseTable

Parse tables whose first row contains labels and later rows are records.

Example

class UserTable(RowTable):
    name = field("name", required=True)

users = UserTable.parse([["name"], ["Alice"]])

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:

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],
    *,
    context: Mapping[str, Any] | ParseContext | None = None,
    error_mode: str = "first",
) -> list[OutputT]
parse_as(
    datatable: RawTable | TableData,
    output_model: None = None,
    *,
    context: Mapping[str, Any] | ParseContext | None = None,
    error_mode: str = "first",
) -> list[Any]
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_model or custom build_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_model is 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:

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.

Example

class ArticleFields(TableFields):
    body = field("Body*", required=True)

RecordSource dataclass ⚓︎

RecordSource(
    item_id: Any | None,
    row: int | None,
    column: int | None,
    cells: Mapping[str, TableCell],
    source_uri: str | None = None,
)

Original table locations associated with one parsed schema record.

Attributes:

  • item_id (Any | None) –

    Parsed local ID for column-oriented records when available.

  • row (int | None) –

    Source row for a row-oriented record.

  • column (int | None) –

    Source key/ID column for a column-oriented record.

  • cells (Mapping[str, TableCell]) –

    Mapping from schema attribute names to their source cells.

  • source_uri (str | None) –

    URI of the source document when known.

Warning

Some fields may not have source cells, especially values produced by defaults for omitted optional fields.

create classmethod ⚓︎

create(
    *,
    item_id: Any | None = None,
    row: int | None = None,
    column: int | None = None,
    cells: Mapping[str, TableCell] | None = None,
    source_uri: str | None = None,
) -> RecordSource

Create immutable metadata from parser-owned source values.

Parameters:

  • item_id (Any | None, default: None ) –

    Parsed record ID when available.

  • row (int | None, default: None ) –

    Source row for row-oriented records.

  • column (int | None, default: None ) –

    Source key/ID column for column-oriented records.

  • cells (Mapping[str, TableCell] | None, default: None ) –

    Mapping from schema field names to source cells.

  • source_uri (str | None, default: None ) –

    URI of the source document when known.

Returns:

  • RecordSource

    A frozen RecordSource with a read-only cell mapping.

Info

The mapping is copied so later caller mutations cannot change record provenance.

source_for ⚓︎

source_for(field_name: str) -> TableCell

Return the source cell for one schema attribute name.

Parameters:

  • field_name (str) –

    Python schema attribute name.

Returns:

  • TableCell

    TableCell that supplied the parsed value.

Raises:

  • KeyError

    If the field has no recorded source cell.

Warning

Missing optional fields with defaults do not have source cells. Use this method when a validator is responding to a value that came from the feature table itself.

TableCell dataclass ⚓︎

TableCell(
    value: str,
    source_row: int,
    source_column: int,
    source_value: str,
    source_uri: str | None = None,
)

One current table value and the feature cell from which it originated.

Attributes:

  • value (str) –

    The value currently consumed by schema parsing. A transformer may change this value.

  • source_row (int) –

    One-based row number of the original Gherkin data table cell.

  • source_column (int) –

    One-based column number of the original Gherkin data table cell.

  • source_value (str) –

    The exact value before any table transformation.

  • source_uri (str | None) –

    URI of the source document when known.

A transformer may produce several cells from one source cell. Each new cell can therefore have a different value while sharing the same source location and source_value.

Example

expanded = source_cell.with_value("Article")
assert expanded.source_value == "3:Article"

__post_init__ ⚓︎

__post_init__() -> None

Validate the immutable source-aware cell boundary.

from_value classmethod ⚓︎

from_value(value: str, *, row: int, column: int) -> TableCell

Create an untransformed cell at a source location.

Parameters:

  • value (str) –

    Raw text from the table.

  • row (int) –

    One-based source row.

  • column (int) –

    One-based source column.

Returns:

  • TableCell

    A TableCell whose current value and source value are the same.

Info

One-based coordinates match feature-file diagnostics and user expectations when reading Gherkin data tables.

with_value ⚓︎

with_value(value: str) -> TableCell

Return a changed cell that still points to this cell's source.

This is the preferred way for a table transformer to replace or expand syntax. For example, a source cell containing 3:Article may produce three cells whose current value is Article while all three still point back to the original 3:Article cell.

Parameters:

  • value (str) –

    New logical value consumed by later parsing stages.

Returns:

  • TableCell

    A new TableCell with updated value and preserved source

  • TableCell

    location/value.

Warning

Constructing fresh cells manually can lose original coordinates. Use this method inside transformers whenever a logical value derives from an existing source cell.

TableData dataclass ⚓︎

TableData(rows: tuple[tuple[TableCell, ...], ...], source_uri: str | None = None)

An immutable, source-aware representation of a Gherkin data table.

TableData intentionally provides only a few explicit operations. It is not a second table-processing framework. Its job is to carry current cell values and original source locations through the schema lifecycle.

Attributes:

  • rows (tuple[tuple[TableCell, ...], ...]) –

    Immutable rows of immutable TableCell tuples.

  • source_uri (str | None) –

    URI of the source document when known.

Info

Direct construction validates every cell and normalizes nested row sequences to tuples, so mutable input lists cannot change the stored table after construction.

__post_init__ ⚓︎

__post_init__() -> None

Validate cells and normalize directly constructed rows to tuples.

from_rows classmethod ⚓︎

from_rows(rows: RawTable, *, source: str | Path | None = None) -> TableData

Wrap ordinary string rows while recording source locations.

Parameters:

  • rows (RawTable) –

    Raw Gherkin data table rows, typically from pytest-bdd.

  • source (str | Path | None, default: None ) –

    Optional URI string or filesystem path for provenance.

Returns:

  • TableData

    A source-aware TableData instance.

Example

table = TableData.from_rows([["name"], ["Alice"]])
assert table.cell(2, 1).source_row == 2

from_cells classmethod ⚓︎

from_cells(
    rows: Sequence[Sequence[TableCell]], *, source: str | Path | None = None
) -> TableData

Build a table from cells whose source information already exists.

Custom transformers use this constructor after arranging existing or transformed cells into their new logical table shape.

Parameters:

  • rows (Sequence[Sequence[TableCell]]) –

    Logical rows of source-aware cells.

  • source (str | Path | None, default: None ) –

    Optional URI string or filesystem path for provenance.

Returns:

  • TableData

    A TableData instance containing immutable row/cell tuples.

Warning

This constructor trusts that cells already preserve useful source information. Prefer cell.with_value(...) when transforming.

ensure classmethod ⚓︎

ensure(table: RawTable | TableData) -> TableData

Return table as TableData.

Parameters:

  • table (RawTable | TableData) –

    Existing source-aware table or raw string rows.

Returns:

  • TableData

    table unchanged when already source-aware, otherwise a new

  • TableData

    TableData created from raw rows.

Info

Schema parsing calls this at the boundary so downstream code can work only with source-aware cells.

cell ⚓︎

cell(row: int, column: int) -> TableCell

Return a cell using one-based row and column indexes.

One-based indexes match the coordinates shown in Gherkin data table errors and make transformer code easier to compare with a feature file.

Parameters:

  • row (int) –

    One-based row number.

  • column (int) –

    One-based column number.

Returns:

Raises:

  • IndexError

    If indexes are less than one or outside the table.

Warning

This helper is for human-facing coordinates. Use rows directly for zero-based Python iteration.

to_rows ⚓︎

to_rows() -> list[list[str]]

Return current values as ordinary mutable string rows.

Returns:

  • list[list[str]]

    A new list[list[str]] containing each cell's current value.

Info

Source metadata is intentionally dropped. This method is useful for display, debugging, and compatibility with code expecting raw rows.

with_source ⚓︎

with_source(source: str | Path) -> TableData

Return this table with normalized source provenance attached.

TableTransformer ⚓︎

Bases: Protocol

Structural contract implemented by reusable table transformers.

Info

Any object with a compatible transform method satisfies this protocol; inheritance is not required.

transform ⚓︎

transform(
    table: TableData, context: ParseContext, *, schema: type | str | None = None
) -> TableData

Return a source-aware table for the next transformation stage.

Parameters:

  • table (TableData) –

    Current source-aware logical table.

  • context (ParseContext) –

    Parse context for the current operation.

  • schema (type | str | None, default: None ) –

    Optional schema identity for diagnostics.

Returns:

Warning

Return TableData, not raw rows. Use TableData.from_cells after arranging source-aware cells.

TransformerPipeline ⚓︎

TransformerPipeline(transformers: Sequence[TableTransformer])

Run table transformers from left to right.

Each stage receives the previous stage's TableData and the same parse context. Unexpected failures identify the stage, while intentional TableError diagnostics pass through unchanged.

Attributes:

  • transformers

    Immutable ordered transformation stages.

Example

table_transformer = compose_transformers(
    NormalizeLabels(),
    ColumnGroupExpander(...),
)

Validate and store transformation stages.

Parameters:

Raises:

  • ValueError

    If no transformers are supplied.

  • TypeError

    If a stage lacks a callable transform method.

Warning

Pipeline order is observable because each stage receives the previous stage's output.

transform ⚓︎

transform(
    table: TableData, context: ParseContext, *, schema: type | str | None = None
) -> TableData

Apply every configured transformer and validate each result.

Parameters:

  • table (TableData) –

    Initial source-aware table.

  • context (ParseContext) –

    Parse context for the current operation.

  • schema (type | str | None, default: None ) –

    Optional schema identity for diagnostics.

Returns:

  • TableData

    Final TableData produced by the last stage.

Raises:

  • TableError

    If a stage raises a table error, raises an unexpected exception, or returns a non-TableData value.

Info

Intentional TableError instances are re-raised unchanged so custom transformers keep their precise source diagnostics.

check_feature ⚓︎

check_feature(
    path: str | Path,
    *,
    schema: type[BaseTable],
    step: str | None = None,
    scenario: str | None = None,
    context: Mapping[str, Any] | None = None,
) -> list[FeatureDiagnostic]

Validate matching feature tables without executing pytest scenarios.

Custom parsers and validators still run. Projects whose schemas require services should supply deterministic checking dependencies through context or through the CLI's context-factory option.

Parameters:

  • path (str | Path) –

    Feature file path.

  • schema (type[BaseTable]) –

    Schema used to parse matching data tables.

  • step (str | None, default: None ) –

    Optional exact step text filter.

  • scenario (str | None, default: None ) –

    Optional exact scenario/background name filter.

  • context (Mapping[str, Any] | None, default: None ) –

    Optional project data passed to schema parsing.

Returns:

Warning

Custom validation code executes during checking. Keep context factories deterministic and free of external side effects in CI/editor workflows.

discover_feature_tables ⚓︎

discover_feature_tables(
    path: str | Path, *, step: str | None = None, scenario: str | None = None
) -> list[FeatureTable]

Return matching feature-file data tables.

Parameters:

  • path (str | Path) –

    Feature file path.

  • step (str | None, default: None ) –

    Optional exact step text filter.

  • scenario (str | None, default: None ) –

    Optional exact scenario/background name filter.

Returns:

Raises:

  • TableError

    If discovery cannot read or compile the feature file.

Example

tables = discover_feature_tables("users.feature", step="the users:")

compose_cell_dsls ⚓︎

compose_cell_dsls(*dsls: CellDSL) -> CellDSLChain

Compose reusable and project-specific cell grammars.

Parameters:

  • *dsls (CellDSL, default: () ) –

    Ordered DSLs, with earlier DSLs taking priority.

Returns:

Example

parser = compose_cell_dsls(shared_cells, article_cells)
headline = field("Headline*", parser=parser)

discriminator ⚓︎

discriminator(
    label: str,
    *,
    variants: Mapping[Any, type],
    parser: Parser | None = None,
    aliases: Sequence[str] = (),
) -> Any

Declare a discriminator and variant field components together.

variants maps parsed discriminator values to TableFields subclasses. When the containing table schema is created, talika composes each component with that schema and registers the resulting record variant automatically.

This is the concise alternative to discriminator_field() plus @Table.variant(value) classes. The explicit decorator form remains useful when a project prefers named variant schema classes.

Parameters:

  • label (str) –

    Canonical discriminator label.

  • variants (Mapping[Any, type]) –

    Mapping from parsed discriminator values to TableFields component classes.

  • parser (Parser | None, default: None ) –

    Optional parser that runs before variant lookup.

  • aliases (Sequence[str], default: () ) –

    Alternate accepted labels.

Returns:

  • Any

    A required discriminator Field descriptor with variant metadata.

Raises:

Example

content_type = discriminator(
    "Type*",
    variants={"Article": ArticleFields, "Poll": PollFields},
)

discriminator_field ⚓︎

discriminator_field(
    label: str, *, parser: Parser | None = None, aliases: Sequence[str] = ()
) -> Any

Declare the field used to select registered record variants.

A discriminator is always required because the parser cannot choose a variant without it. The optional parser runs before variant lookup, so a project may register enum members or other typed values as variant keys.

Declaring this field does not enable variants by itself. Register variant schema subclasses with @BaseSchema.variant(value).

Parameters:

  • label (str) –

    Canonical discriminator label.

  • parser (Parser | None, default: None ) –

    Optional parser that runs before variant lookup.

  • aliases (Sequence[str], default: () ) –

    Alternate accepted labels.

Returns:

  • Any

    A required discriminator Field descriptor.

Example

class ContentTable(ColumnTable):
    content_type = discriminator_field("Type*")

field ⚓︎

field(
    label: str | None = None,
    *,
    required: bool = False,
    default: Any = MISSING,
    default_factory: DefaultFactory | object = MISSING,
    parser: Parser | None = None,
    aliases: Sequence[str] = (),
    empty: str | None = None,
) -> Any

Declare a row or column in a table schema.

The Python attribute name becomes the table label when label is omitted. Empty cells are controlled only by empty; parser objects do not opt into blank handling implicitly.

Parameters:

  • label (str | None, default: None ) –

    Canonical Gherkin data table label. When omitted, use the Python attribute name.

  • required (bool, default: False ) –

    Whether the field must be present and non-empty.

  • default (Any, default: MISSING ) –

    Static value used when the entire field is absent.

  • default_factory (DefaultFactory | object, default: MISSING ) –

    Factory called for an absent optional field.

  • parser (Parser | None, default: None ) –

    Optional parser for non-empty values.

  • aliases (Sequence[str], default: () ) –

    Alternate accepted table labels.

  • empty (str | None, default: None ) –

    Policy for explicit empty cells. When omitted, required fields use "error" and optional fields use "raw". "parse" sends an empty string through the parser, "none" returns None, and "error" rejects it.

Returns:

  • Any

    A descriptor collected by RowTable or ColumnTable subclasses.

Raises:

  • TypeError

    If labels, aliases, parsers, factories, or defaults have an invalid runtime shape.

  • ValueError

    If required/default/empty options contradict each other or an empty policy is unknown.

Example

class UserTable(RowTable):
    name = field(required=True)
    role = field("role", default="viewer", aliases=("type",))

id_field ⚓︎

id_field(
    label: str, *, parser: Parser | None = None, aliases: Sequence[str] = ()
) -> Any

Declare the item identifier field for parsed records.

Parameters:

  • label (str) –

    Canonical ID row label.

  • parser (Parser | None, default: None ) –

    Optional parser for ID values.

  • aliases (Sequence[str], default: () ) –

    Alternate accepted ID row labels.

Returns:

  • Any

    A required identifier Field descriptor.

Warning

A column-oriented table must declare exactly one ID field. A row-oriented table may declare one when parser contexts, defaults, and diagnostics need a stable item_id.

reference ⚓︎

reference(
    label: str,
    *,
    target: str = "id",
    many: bool = False,
    separator: str = ",",
    required: bool = False,
    default: Any = MISSING,
    aliases: Sequence[str] = (),
) -> Any

Declare a local reference to another parsed record in the same table.

The raw cell contains one target value, or a separator-delimited list when many=True. Resolution occurs after all records are constructed and before validation hooks run.

Parameters:

  • label (str) –

    Canonical table label containing reference keys.

  • target (str, default: 'id' ) –

    Attribute on records used as the lookup key.

  • many (bool, default: False ) –

    Whether the cell contains several keys.

  • separator (str, default: ',' ) –

    Separator used when many is true.

  • required (bool, default: False ) –

    Whether the reference cell must be present and non-empty.

  • default (Any, default: MISSING ) –

    Static value used when an optional reference field is absent.

  • aliases (Sequence[str], default: () ) –

    Alternate accepted table labels.

Returns:

  • Any

    A Field descriptor whose parsed value is resolved to record

  • Any

    objects.

Raises:

  • ValueError

    If many=True and separator is empty.

Warning

Reference keys are parsed with the target field's parser before lookup. Keep separators distinct from valid key text when using many=True.

boolean ⚓︎

boolean(
    *,
    true_values: Iterable[str] = ("true",),
    false_values: Iterable[str] = ("false",),
    case_sensitive: bool = False,
) -> Parser

Return a boolean parser with an explicit accepted vocabulary.

Parameters:

  • true_values (Iterable[str], default: ('true',) ) –

    Strings accepted as True.

  • false_values (Iterable[str], default: ('false',) ) –

    Strings accepted as False.

  • case_sensitive (bool, default: False ) –

    Whether matching should preserve case.

Returns:

  • Parser

    A parser that returns bool.

Raises:

  • TypeError

    If token collections or case_sensitive have invalid types.

  • ValueError

    If the true and false token sets overlap.

The default vocabulary is deliberately small

Without configuration, the parser accepts only "true" and "false". Matching is case-insensitive by default, so "TRUE" and "False" also work. Words such as "yes" and "on" and numeric flags such as "1" must be declared by the schema.

Warning

Unknown values fail instead of falling back to Python truthiness. This prevents cells such as "False" or "nope" from accidentally becoming true.

Whitespace is not removed

" true " is different from "true". Compose string(strip=True) before this parser when the authored format permits padding.

Example

active = field(
    "active",
    parser=boolean(true_values=("Y",), false_values=("N",)),
)

choice ⚓︎

choice(*values: str, case_sensitive: bool = True) -> Parser

Return a parser that validates one allowed string value.

Parameters:

  • *values (str, default: () ) –

    Accepted display values.

  • case_sensitive (bool, default: True ) –

    Whether input must match the case of an accepted value.

Returns:

  • Parser

    A parser that returns the canonical value from values.

Raises:

Info

With case_sensitive=False, the returned value is still the canonical spelling passed to the factory.

Example

role = field("role", parser=choice("admin", "editor", "viewer"))

compose ⚓︎

compose(*parsers: Parser) -> Parser

Run parsers left-to-right.

Parameters:

  • *parsers (Parser, default: () ) –

    Parser callables following the talika parser contract.

Returns:

  • Parser

    A parser that feeds each result into the next parser.

Raises:

Info

Every parser receives the same CellContext so later stages still know the original field, item ID, and source value.

Example

scores = field("scores", parser=compose(split(","), each(integer())))

decimal ⚓︎

decimal() -> Parser

Return a parser that converts through text to Decimal.

Returns:

  • Parser

    A parser that returns decimal.Decimal.

Info

Conversion goes through str(value) so existing numeric objects and raw table text follow the same exact decimal path.

Example

class PriceTable(RowTable):
    total = field("total", parser=decimal())

each ⚓︎

each(parser: Parser) -> Parser

Apply one parser to every item in an iterable value.

Parameters:

  • parser (Parser) –

    Parser applied to each non-string item.

Returns:

  • Parser

    A parser that returns list[Any].

Info

each() is designed for composition after parsers that produce a sequence, such as split().

Example

ids = field("ids", parser=compose(split(","), each(integer())))

floating ⚓︎

floating() -> Parser

Return a parser that converts values to float.

Returns:

  • Parser

    A parser that returns a Python float.

Warning

Use decimal() instead when tests need exact decimal arithmetic or should avoid binary floating-point representation.

Example

class Product(RowTable):
    rating = field("rating", parser=floating())

integer ⚓︎

integer(*, base: int = 10) -> Parser

Return a parser that converts values to int.

Parameters:

  • base (int, default: 10 ) –

    Numeric base used when the incoming value is a string.

Returns:

  • Parser

    A parser that returns an integer.

Warning

The base is passed to Python's int(value, base) only for strings. Non-string values use int(value) so already-typed project values still follow Python's normal conversion rules.

Example

class Flags(RowTable):
    mask = field("mask", parser=integer(base=16))

map_value ⚓︎

map_value(values: Mapping[str, Any], *, case_sensitive: bool = True) -> Parser

Return a parser that maps cell strings to Python values.

Parameters:

  • values (Mapping[str, Any]) –

    Mapping from table text to the Python value to return.

  • case_sensitive (bool, default: True ) –

    Whether lookup should preserve case.

Returns:

  • Parser

    A parser that returns the mapped value.

Info

This is useful for compact BDD vocabulary such as "TBD" becoming a sentinel object or "high" becoming a domain enum value.

Example

priority = field("priority", parser=map_value({"low": 1, "high": 3}))

optional ⚓︎

optional(
    parser: Parser,
    *,
    none_values: Iterable[str] = ("none", "null"),
    case_sensitive: bool = False,
) -> Parser

Return a parser that maps empty or null-like tokens to None.

Parameters:

  • parser (Parser) –

    Parser used for non-null values.

  • none_values (Iterable[str], default: ('none', 'null') ) –

    Text tokens that should parse as None.

  • case_sensitive (bool, default: False ) –

    Whether matching none_values should preserve case.

Returns:

  • Parser

    A parser object that converts empty or configured null-like values to

  • Parser

    None when the field invokes it.

Info

Use field(..., empty="parse") when an explicit blank cell should reach the returned parser. Without that field policy, blanks follow the field's normal empty-cell behavior.

Example

due_date = field("due", parser=optional(string(strip=True)))

split ⚓︎

split(
    separator: str = ",", *, strip_items: bool = True, keep_empty: bool = False
) -> Parser

Return a parser that splits one cell into a list of strings.

Parameters:

  • separator (str, default: ',' ) –

    Text separator used between items.

  • strip_items (bool, default: True ) –

    Strip whitespace around each split item.

  • keep_empty (bool, default: False ) –

    Preserve empty segments instead of filtering them out.

Returns:

  • Parser

    A parser that returns list[str].

Raises:

Info

This parser is often paired with each(...) when a table cell holds a compact list of typed values.

Example

tags = field("tags", parser=split(","))

string ⚓︎

string(*, strip: bool = False, lower: bool = False, upper: bool = False) -> Parser

Return a parser that normalizes text.

Parameters:

  • strip (bool, default: False ) –

    Remove leading and trailing whitespace before case conversion.

  • lower (bool, default: False ) –

    Convert the resulting text to lowercase.

  • upper (bool, default: False ) –

    Convert the resulting text to uppercase.

Returns:

  • Parser

    A parser that always returns str.

Raises:

  • ValueError

    If both lower and upper are enabled.

Warning

This parser deliberately performs no semantic validation. Use choice() or a custom parser when the table cell must be one of a known set of values.

Example

class UserTable(RowTable):
    role = field("role", parser=string(strip=True, lower=True))

parse_table ⚓︎

parse_table(
    schema: type[TableT],
    datatable: RawTable | TableData,
    *,
    context: Mapping[str, Any] | ParseContext | None = None,
    error_mode: str = "first",
) -> list[TableT]

Parse a Gherkin data table using a schema class.

This is the functional equivalent of schema.parse(datatable). It is useful in codebases that prefer explicit parser functions over classmethod calls. It always returns validated schema records; output conversion uses :func:parse_table_as.

Parameters:

  • schema (type[TableT]) –

    Concrete RowTable or ColumnTable subclass.

  • datatable (RawTable | TableData) –

    Raw list[list[str]] table 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" for fail-fast parsing or "collect" for aggregate diagnostics.

Returns:

  • list[TableT]

    Validated instances of schema.

Raises:

Note

Warning-severity validation diagnostics are emitted as TalikaWarning and records are still returned.

Example

users = parse_table(UserTable, datatable)

parse_table_as ⚓︎

parse_table_as(
    schema: type[BaseTable],
    datatable: RawTable | TableData,
    output_model: Callable[..., OutputT],
    *,
    context: Mapping[str, Any] | ParseContext | None = None,
    error_mode: str = "first",
) -> list[OutputT]
parse_table_as(
    schema: type[BaseTable],
    datatable: RawTable | TableData,
    output_model: None = None,
    *,
    context: Mapping[str, Any] | ParseContext | None = None,
    error_mode: str = "first",
) -> list[Any]
parse_table_as(
    schema: type[BaseTable],
    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 Gherkin data table and build public output objects.

This is the functional equivalent of schema.parse_as(...). An explicit callable overrides configured schema and variant output hooks. Omitting it uses the schema's output_model or custom build_output().

Parameters:

  • schema (type[BaseTable]) –

    Concrete RowTable or ColumnTable subclass.

  • datatable (RawTable | TableData) –

    Raw list[list[str]] table or source-aware TableData.

  • output_model (Callable[..., OutputT] | None, default: None ) –

    Optional callable receiving parsed record fields as keyword arguments.

  • context (Mapping[str, Any] | ParseContext | None, default: None ) –

    Optional project data or existing parse context.

  • error_mode (str, default: 'first' ) –

    "first" for fail-fast parsing or "collect" for aggregate diagnostics.

Returns:

  • list[OutputT] | list[Any]

    Converted public output objects.

Raises:

  • TypeError

    If output_model is not callable.

  • ValueError

    If no explicit or configured output conversion exists.

  • TableError

    If parsing, validation, or output construction fails.

  • TableErrors

    If collect mode finds multiple failures.

Note

Warning-severity validation diagnostics are emitted as TalikaWarning and converted objects are still returned.

validate_table ⚓︎

validate_table(
    schema: type[TableT],
    datatable: RawTable | TableData,
    *,
    context: Mapping[str, Any] | ParseContext | None = None,
) -> ValidationResult[TableT]

Validate a table and return records or diagnostics without raising.

This is the functional equivalent of schema.validate(datatable). Output-model conversion is skipped, and invalid results never expose partially parsed records.

Parameters:

  • schema (type[TableT]) –

    Concrete RowTable or ColumnTable subclass.

  • 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 frozen validation result containing complete records and ordered

  • ValidationResult[TableT]

    diagnostics. Warning-only results remain valid and retain records.

Note

Schema declaration errors and API misuse still raise because they are not authored table-data diagnostics.

compose_transformers ⚓︎

compose_transformers(*transformers: TableTransformer) -> TransformerPipeline

Create a reusable left-to-right table transformation pipeline.

Parameters:

  • *transformers (TableTransformer, default: () ) –

    Ordered transformer stages.

Returns:

Example

class ContentTable(ColumnTable):
    table_transformer = compose_transformers(clean, expand)