Skip to content

CellDSL⚓︎

dsl ⚓︎

Composable, project-owned cell parsing rules.

CellDSL intentionally implements dispatch rather than domain syntax. A project chooses its exact tokens, regular expressions, predicates, field scopes, generated values, and fallback behavior.

Info

The DSL is a parser factory for one field value at a time. It never changes table shape, performs business actions, or interprets symbols such as * unless a project registers that meaning.

_TokenRule dataclass ⚓︎

_TokenRule(value: str, fields: frozenset[str] | None, handler: TokenHandler)

Registered exact-token rule used by CellDSL dispatch.

Attributes:

  • value (str) –

    Exact cell text that triggers this rule.

  • fields (frozenset[str] | None) –

    Optional schema-field scope.

  • handler (TokenHandler) –

    Callable that produces the parsed value.

Info

Token rules are internal immutable records so registration order and duplicate detection remain separate concerns.

_PatternRule dataclass ⚓︎

_PatternRule(
    source: str,
    pattern: Pattern[str],
    fields: frozenset[str] | None,
    handler: PatternHandler,
)

Registered full-match regular-expression rule.

Attributes:

  • source (str) –

    Original pattern text used for duplicate detection.

  • pattern (Pattern[str]) –

    Compiled regular expression.

  • fields (frozenset[str] | None) –

    Optional schema-field scope.

  • handler (PatternHandler) –

    Callable receiving the match and cell context.

Warning

Patterns use fullmatch during dispatch. Add .* explicitly when a project really wants substring behavior.

_PredicateRule dataclass ⚓︎

_PredicateRule(
    predicate: Predicate, fields: frozenset[str] | None, handler: PredicateHandler
)

Registered project predicate and matching handler.

Attributes:

  • predicate (Predicate) –

    Callable deciding whether a value should be handled.

  • fields (frozenset[str] | None) –

    Optional schema-field scope.

  • handler (PredicateHandler) –

    Callable receiving the original value and context.

Warning

Predicate functions should be side-effect free. They may be evaluated for cells that ultimately match only because the predicate returns true.

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.

_normalize_fields ⚓︎

_normalize_fields(fields: Iterable[str] | None) -> frozenset[str] | None

Return an immutable field-name scope for one rule declaration.

Parameters:

  • fields (Iterable[str] | None) –

    None for a global rule, one field name, or an iterable of field names.

Returns:

  • frozenset[str] | None

    None for a global rule or a non-empty immutable field-name set.

Raises:

  • ValueError

    If a scoped rule contains no usable field names.

Warning

Scopes use schema attribute names, not human-facing table labels.

_applies ⚓︎

_applies(fields: frozenset[str] | None, context: CellContext) -> bool

Return whether a rule is global or includes the current schema field.

Parameters:

  • fields (frozenset[str] | None) –

    Normalized field scope or None for a global rule.

  • context (CellContext) –

    Parser context for the cell being dispatched.

Returns:

  • bool

    True when the rule should be considered for the active field.

Info

Field scoping happens before pattern matching and predicate execution, so expensive project predicates can be limited to relevant fields.

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)