Skip to content

Recipe

🛈 DocStrings

Source code in src/datacook/engine/recipes.py
@dataclass(frozen=True, slots=True)
class Recipe:
    name: str
    steps: tuple[RecipeStep, ...]
    description: str = ""
    required_columns: tuple[str, ...] = ()
    created: str = field(default_factory=_now)
    datacook: str = field(default_factory=_version)
    """DataCook version that wrote the recipe."""

    @property
    def is_import(self) -> bool:
        """No step reads the input: the recipe starts with a reader (apply it to files)."""
        return not any(INPUT in s.inputs for s in self.steps)

    def leaves(self) -> list[int]:
        """Indexes of the steps no other step consumes."""
        used = {i for s in self.steps for i in s.inputs if isinstance(i, int)}
        return [i for i in range(len(self.steps)) if i not in used]

    def sources(self) -> list[int]:
        """Indexes of the steps without inputs (readers)."""
        return [i for i, s in enumerate(self.steps) if not s.inputs]

    def missing_columns(self, columns: Iterable[str]) -> list[str]:
        available = set(columns)
        return [c for c in self.required_columns if c not in available]

    def validate(self, registry: Registry[type[Op]]) -> None:
        """Structure check (input indexes, input counts); raises `RecipeError`."""
        if not self.steps:
            raise RecipeError(str(_("A recipe needs at least one step.")))
        for i, step in enumerate(self.steps):
            try:
                op = registry[step.record.op_id]
            except KeyError as e:
                msg = _("Step {index}: unknown operation {op!r}")
                raise RecipeError(str(msg).format(index=i + 1, op=step.record.op_id)) from e
            if not op.takes(len(step.inputs)):
                msg = _("Step {index}: {op} takes {n} input(s)")
                raise RecipeError(str(msg).format(index=i + 1, op=op.id, n=op.inputs_text()))
            for ref in step.inputs:
                if ref != INPUT and not (isinstance(ref, int) and 0 <= ref < i):
                    msg = _("Step {index}: invalid input {ref!r}")
                    raise RecipeError(str(msg).format(index=i + 1, ref=ref))

    # --- serialisation -----------------------------------------------------------------
    def to_dict(self) -> dict[str, Any]:
        return {
            "format": FORMAT,
            "version": VERSION,
            "name": self.name,
            "description": self.description,
            "created": self.created,
            "datacook": self.datacook,
            "required_columns": list(self.required_columns),
            "steps": [
                {
                    **s.record.to_json(),
                    "inputs": list(s.inputs),
                    "name": s.name,
                    "comment": s.comment,
                }
                for s in self.steps
            ],
        }

    def dumps(self) -> str:
        return json.dumps(self.to_dict(), indent=2, ensure_ascii=False)

    def save(self, path: str | pathlib.Path) -> None:
        pathlib.Path(path).write_text(self.dumps() + "\n", encoding="utf-8")

datacook class-attribute instance-attribute

datacook: str = field(default_factory=_version)

DataCook version that wrote the recipe.

is_import property

is_import: bool

No step reads the input: the recipe starts with a reader (apply it to files).

leaves

leaves() -> list[int]

Indexes of the steps no other step consumes.

Source code in src/datacook/engine/recipes.py
def leaves(self) -> list[int]:
    """Indexes of the steps no other step consumes."""
    used = {i for s in self.steps for i in s.inputs if isinstance(i, int)}
    return [i for i in range(len(self.steps)) if i not in used]

sources

sources() -> list[int]

Indexes of the steps without inputs (readers).

Source code in src/datacook/engine/recipes.py
def sources(self) -> list[int]:
    """Indexes of the steps without inputs (readers)."""
    return [i for i, s in enumerate(self.steps) if not s.inputs]

validate

validate(registry: Registry[type[Op]]) -> None

Structure check (input indexes, input counts); raises RecipeError.

Source code in src/datacook/engine/recipes.py
def validate(self, registry: Registry[type[Op]]) -> None:
    """Structure check (input indexes, input counts); raises `RecipeError`."""
    if not self.steps:
        raise RecipeError(str(_("A recipe needs at least one step.")))
    for i, step in enumerate(self.steps):
        try:
            op = registry[step.record.op_id]
        except KeyError as e:
            msg = _("Step {index}: unknown operation {op!r}")
            raise RecipeError(str(msg).format(index=i + 1, op=step.record.op_id)) from e
        if not op.takes(len(step.inputs)):
            msg = _("Step {index}: {op} takes {n} input(s)")
            raise RecipeError(str(msg).format(index=i + 1, op=op.id, n=op.inputs_text()))
        for ref in step.inputs:
            if ref != INPUT and not (isinstance(ref, int) and 0 <= ref < i):
                msg = _("Step {index}: invalid input {ref!r}")
                raise RecipeError(str(msg).format(index=i + 1, ref=ref))

:fa-brands-github: Show source on GitHub