Skip to content

ops

Class info

Re-exported classes

Class Module Description
CallOp datacook.engine.ops.base An op that is one pandas call.
Match datacook.engine.ops.base A recognised statement: the op's params, input variables and output variable.
NoParams datacook.engine.ops.base
Op datacook.engine.ops.base Base class for operations. Subclasses set the metadata class variables.
OpError datacook.engine.ops.base An op failed to apply (wraps the backend's exception).
OpRecord datacook.engine.ops.base What a node stores: the op id plus its (immutable) params.
Params datacook.engine.ops.base Base for op parameters: immutable, unknown keys rejected.
Registry datacook.engine.registry

🛈 DocStrings

Operations: Op classes, op records and the op registry (entry point group datacook.ops).

CallOp

Bases: Op

An op that is one pandas call.

Either method (called on the first input, remaining inputs as leading positional arguments: out = a.merge(b, how="left")) or function (a dotted name in the generated code, all inputs as leading positional arguments: out = pd.read_csv("x.csv")). Params named in positional are passed positionally; the other params are passed as keywords when they differ from their default.

Source code in src/datacook/engine/ops/base.py
class CallOp(Op):
    """An op that is one pandas call.

    Either `method` (called on the first input, remaining inputs as leading positional
    arguments: `out = a.merge(b, how="left")`) or `function` (a dotted name in the generated
    code, all inputs as leading positional arguments: `out = pd.read_csv("x.csv")`).
    Params named in `positional` are passed positionally; the other params are passed as
    keywords when they differ from their default.
    """

    method: ClassVar[str | None] = None
    function: ClassVar[str | None] = None
    positional: ClassVar[tuple[str, ...]] = ()
    always: ClassVar[tuple[str, ...]] = ()
    """Params passed even when they equal their default (defaults that differ from pandas)."""
    fixed: ClassVar[Mapping[str, Any]] = MappingProxyType({})
    """Keyword arguments that are not params, always passed first (e.g. `axis="columns"`)."""
    then: ClassVar[str] = ""
    """Code appended to the call (`".reset_index()"`); `finish()` does the same in `apply`."""

    @classmethod
    def finish(cls, params: Any, result: Any) -> Any:
        """What `then` does, applied to the call's result."""
        return result

    @classmethod
    def call_args(cls, params: Params) -> tuple[list[Any], dict[str, Any]]:
        args, kwargs = call_arguments(params, cls.positional, cls.always)
        return args, {**cls.fixed, **kwargs}

    @classmethod
    def params_from_call(cls, args: list[Any], kwargs: dict[str, Any]) -> Params | None:
        """The params of a call; None if not this op."""
        if len(args) > len(cls.positional):
            msg = f"too many positional arguments for {cls.id}"
            raise ValueError(msg)
        for key, value in cls.fixed.items():
            if key not in kwargs or kwargs.pop(key) != value:
                return None
        if not set(kwargs) <= set(cls.Params.model_fields):
            return None  # e.g. `dropna(axis="columns")` is not "drop rows with missing values"
        return cls.Params(**dict(zip(cls.positional, args)), **kwargs)

    @classmethod
    def _callable(cls, inputs: Sequence[Frame]) -> Any:
        if cls.method is not None:
            return getattr(inputs[0], cls.method)
        assert cls.function is not None
        module, _sep, name = cls.function.rpartition(".")
        namespace = {"pd": "pandas"}
        import importlib

        obj: Any = importlib.import_module(namespace.get(module, module))
        return getattr(obj, name)

    @classmethod
    def apply(cls, params: Any, *inputs: Frame) -> Frame:
        args, kwargs = cls.call_args(params)
        frame_args = inputs[1:] if cls.method is not None else inputs
        result = cls.finish(params, cls._callable(inputs)(*frame_args, *args, **kwargs))
        if not frames.is_frame(result):
            msg = f"{cls.id} returned {type(result).__name__}, not a frame"
            raise OpError(msg)
        return result

    @classmethod
    def to_code(cls, params: Any, inputs: Sequence[str], output: str) -> str:
        args, kwargs = cls.call_args(params)
        if cls.method is not None:
            func = f"{inputs[0]}.{cls.method}"
            frame_args = list(inputs[1:])
        else:
            assert cls.function is not None
            func = cls.function
            frame_args = list(inputs)
        width = len(output) + 3 + len(cls.then)  # the tail goes on the last line
        call = format_call(func, [*frame_args, *map(literal, args)], kwargs, width)
        return f"{output} = {call}{cls.then}"

    @classmethod
    def literal_args(cls, call: ast.Call, skip: int = 0) -> tuple[list[Any], dict[str, Any]] | None:
        """Literal positional (after `skip`) and keyword arguments of a call, else None."""
        if any(kw.arg is None for kw in call.keywords):
            return None
        try:
            args = [literal_value(a) for a in call.args[skip:]]
            kwargs = {kw.arg: literal_value(kw.value) for kw in call.keywords if kw.arg}
        except ValueError:  # not literal: user code, kept as custom code
            return None
        return args, kwargs

    @classmethod
    def from_code(  # noqa: PLR0911
        cls, stmt: ast.stmt, bound: Mapping[str, Any]
    ) -> Match | None:
        assign = assignment(stmt)
        if assign is None:
            return None
        output, value = assign
        if cls.then:
            value = strip_tail(value, cls.then)
        if not isinstance(value, ast.Call):
            return None
        func = dotted_name(value.func)
        if func is None:
            return None
        n_frames = cls.n_inputs
        if cls.method is not None:
            base, _sep, attr = func.rpartition(".")
            if attr != cls.method or base not in bound:
                return None
            inputs = [base]
            n_frames -= 1
        elif func == cls.function:
            inputs = []
        else:
            return None
        frame_nodes = value.args[:n_frames]
        if len(frame_nodes) < n_frames or not all(
            isinstance(a, ast.Name) and a.id in bound for a in frame_nodes
        ):
            return None
        inputs += [a.id for a in frame_nodes if isinstance(a, ast.Name)]
        found = cls.literal_args(value, n_frames)
        if found is None:
            return None
        params = cls.params_from_call(*found)
        return None if params is None else Match(params, tuple(inputs), output)

always class-attribute

always: tuple[str, ...] = ()

Params passed even when they equal their default (defaults that differ from pandas).

fixed class-attribute

fixed: Mapping[str, Any] = MappingProxyType({})

Keyword arguments that are not params, always passed first (e.g. axis="columns").

then class-attribute

then: str = ''

Code appended to the call (".reset_index()"); finish() does the same in apply.

finish classmethod

finish(params: Any, result: Any) -> Any

What then does, applied to the call's result.

Source code in src/datacook/engine/ops/base.py
@classmethod
def finish(cls, params: Any, result: Any) -> Any:
    """What `then` does, applied to the call's result."""
    return result

literal_args classmethod

literal_args(call: Call, skip: int = 0) -> tuple[list[Any], dict[str, Any]] | None

Literal positional (after skip) and keyword arguments of a call, else None.

Source code in src/datacook/engine/ops/base.py
@classmethod
def literal_args(cls, call: ast.Call, skip: int = 0) -> tuple[list[Any], dict[str, Any]] | None:
    """Literal positional (after `skip`) and keyword arguments of a call, else None."""
    if any(kw.arg is None for kw in call.keywords):
        return None
    try:
        args = [literal_value(a) for a in call.args[skip:]]
        kwargs = {kw.arg: literal_value(kw.value) for kw in call.keywords if kw.arg}
    except ValueError:  # not literal: user code, kept as custom code
        return None
    return args, kwargs

params_from_call classmethod

params_from_call(args: list[Any], kwargs: dict[str, Any]) -> Params | None

The params of a call; None if not this op.

Source code in src/datacook/engine/ops/base.py
@classmethod
def params_from_call(cls, args: list[Any], kwargs: dict[str, Any]) -> Params | None:
    """The params of a call; None if not this op."""
    if len(args) > len(cls.positional):
        msg = f"too many positional arguments for {cls.id}"
        raise ValueError(msg)
    for key, value in cls.fixed.items():
        if key not in kwargs or kwargs.pop(key) != value:
            return None
    if not set(kwargs) <= set(cls.Params.model_fields):
        return None  # e.g. `dropna(axis="columns")` is not "drop rows with missing values"
    return cls.Params(**dict(zip(cls.positional, args)), **kwargs)

Match dataclass

A recognised statement: the op's params, input variables and output variable.

Source code in src/datacook/engine/ops/base.py
@dataclass(frozen=True, slots=True)
class Match:
    """A recognised statement: the op's params, input variables and output variable."""

    params: Params
    inputs: tuple[str, ...]
    output: str

Op

Base class for operations. Subclasses set the metadata class variables.

Source code in src/datacook/engine/ops/base.py
class Op:
    """Base class for operations. Subclasses set the metadata class variables."""

    id: ClassVar[str]
    title: ClassVar[LazyText]
    description: ClassVar[LazyText] = LazyText("")  # no msgid: not in the catalog
    category: ClassVar[Category] = categories.GENERAL
    icon: ClassVar[str] = "mdi.function"
    Params: ClassVar[type[Params]] = NoParams
    n_inputs: ClassVar[int] = 1
    """Number of parent frames: 0 = source (reader), 2 = merge, ..."""
    variadic: ClassVar[bool] = False
    """`n_inputs` or more parent frames (concat)."""
    backend: ClassVar[Backend] = "pandas"
    imports: ClassVar[tuple[str, ...]] = ("import pandas as pd",)
    """Import lines the generated code needs."""
    requires: ClassVar[tuple[str, ...]] = ()
    """Importable modules needed at runtime (optional dependencies)."""
    extra: ClassVar[str | None] = None
    """The package extra that installs `requires`."""

    # --- execution -------------------------------------------------------------------
    @classmethod
    def apply(cls, params: Any, *inputs: Frame) -> Frame:
        raise NotImplementedError

    # --- code ------------------------------------------------------------------------
    @classmethod
    def to_code(cls, params: Any, inputs: Sequence[str], output: str) -> str:
        """Python statement(s) computing `output` from the input variables."""
        raise NotImplementedError

    @classmethod
    def to_code_block(cls, params: Any, inputs: Sequence[str], output: str, used: set[str]) -> str:
        """Like `to_code`, with the script's already-used variable names (for unique locals)."""
        return cls.to_code(params, inputs, output)

    @classmethod
    def from_code(cls, stmt: ast.stmt, bound: Mapping[str, Any]) -> Match | None:
        """Recognise one statement produced by `to_code`; `bound` = known variable names.

        Return None if the statement is not this op. Raise `ValueError` for a recognised
        statement with invalid params.
        """
        return None

    @classmethod
    def from_block(cls, stmts: Sequence[ast.stmt], bound: Mapping[str, Any]) -> Match | None:
        """Recognise a multi-statement block produced by `to_code` (default: none)."""
        return None

    # --- helpers ---------------------------------------------------------------------
    @classmethod
    def record(cls, params: Params | None = None, /, **kwargs: Any) -> OpRecord:
        return OpRecord(cls.id, params if params is not None else cls.Params(**kwargs))

    @classmethod
    def takes(cls, n: int) -> bool:
        """Whether the op takes `n` input frames."""
        return n == cls.n_inputs or (cls.variadic and n > cls.n_inputs)

    @classmethod
    def inputs_text(cls) -> str:
        """`"2"` or `"2 or more"` (error messages)."""
        return f"{cls.n_inputs} or more" if cls.variadic else str(cls.n_inputs)

    @classmethod
    def imports_for(cls, params: Any) -> tuple[str, ...]:
        """Import lines the generated code needs for `params` (default: `cls.imports`)."""
        return cls.imports

    @classmethod
    def available(cls) -> bool:
        import importlib.util

        return all(importlib.util.find_spec(mod) is not None for mod in cls.requires)

extra class-attribute

extra: str | None = None

The package extra that installs requires.

imports class-attribute

imports: tuple[str, ...] = ('import pandas as pd',)

Import lines the generated code needs.

n_inputs class-attribute

n_inputs: int = 1

Number of parent frames: 0 = source (reader), 2 = merge, ...

requires class-attribute

requires: tuple[str, ...] = ()

Importable modules needed at runtime (optional dependencies).

variadic class-attribute

variadic: bool = False

n_inputs or more parent frames (concat).

from_block classmethod

from_block(stmts: Sequence[stmt], bound: Mapping[str, Any]) -> Match | None

Recognise a multi-statement block produced by to_code (default: none).

Source code in src/datacook/engine/ops/base.py
@classmethod
def from_block(cls, stmts: Sequence[ast.stmt], bound: Mapping[str, Any]) -> Match | None:
    """Recognise a multi-statement block produced by `to_code` (default: none)."""
    return None

from_code classmethod

from_code(stmt: stmt, bound: Mapping[str, Any]) -> Match | None

Recognise one statement produced by to_code; bound = known variable names.

Return None if the statement is not this op. Raise ValueError for a recognised statement with invalid params.

Source code in src/datacook/engine/ops/base.py
@classmethod
def from_code(cls, stmt: ast.stmt, bound: Mapping[str, Any]) -> Match | None:
    """Recognise one statement produced by `to_code`; `bound` = known variable names.

    Return None if the statement is not this op. Raise `ValueError` for a recognised
    statement with invalid params.
    """
    return None

imports_for classmethod

imports_for(params: Any) -> tuple[str, ...]

Import lines the generated code needs for params (default: cls.imports).

Source code in src/datacook/engine/ops/base.py
@classmethod
def imports_for(cls, params: Any) -> tuple[str, ...]:
    """Import lines the generated code needs for `params` (default: `cls.imports`)."""
    return cls.imports

inputs_text classmethod

inputs_text() -> str

"2" or "2 or more" (error messages).

Source code in src/datacook/engine/ops/base.py
@classmethod
def inputs_text(cls) -> str:
    """`"2"` or `"2 or more"` (error messages)."""
    return f"{cls.n_inputs} or more" if cls.variadic else str(cls.n_inputs)

takes classmethod

takes(n: int) -> bool

Whether the op takes n input frames.

Source code in src/datacook/engine/ops/base.py
@classmethod
def takes(cls, n: int) -> bool:
    """Whether the op takes `n` input frames."""
    return n == cls.n_inputs or (cls.variadic and n > cls.n_inputs)

to_code classmethod

to_code(params: Any, inputs: Sequence[str], output: str) -> str

Python statement(s) computing output from the input variables.

Source code in src/datacook/engine/ops/base.py
@classmethod
def to_code(cls, params: Any, inputs: Sequence[str], output: str) -> str:
    """Python statement(s) computing `output` from the input variables."""
    raise NotImplementedError

to_code_block classmethod

to_code_block(params: Any, inputs: Sequence[str], output: str, used: set[str]) -> str

Like to_code, with the script's already-used variable names (for unique locals).

Source code in src/datacook/engine/ops/base.py
@classmethod
def to_code_block(cls, params: Any, inputs: Sequence[str], output: str, used: set[str]) -> str:
    """Like `to_code`, with the script's already-used variable names (for unique locals)."""
    return cls.to_code(params, inputs, output)

OpError

Bases: Exception

An op failed to apply (wraps the backend's exception).

Source code in src/datacook/engine/ops/base.py
class OpError(Exception):
    """An op failed to apply (wraps the backend's exception)."""

OpRecord dataclass

What a node stores: the op id plus its (immutable) params.

Source code in src/datacook/engine/ops/base.py
@dataclass(frozen=True, slots=True)
class OpRecord:
    """What a node stores: the op id plus its (immutable) params."""

    op_id: str
    params: Params

    def to_json(self) -> dict[str, Any]:
        return {"op": self.op_id, "params": self.params.model_dump(mode="json")}

Params

Bases: BaseModel

Base for op parameters: immutable, unknown keys rejected.

Source code in src/datacook/engine/ops/base.py
class Params(pydantic.BaseModel):
    """Base for op parameters: immutable, unknown keys rejected."""

    model_config = pydantic.ConfigDict(frozen=True, extra="forbid")

default_ops cached

default_ops() -> Registry[type[Op]]

The registry of all installed ops (built-ins included), loaded from entry points.

Source code in src/datacook/engine/ops/__init__.py
@functools.cache
def default_ops() -> Registry[type[Op]]:
    """The registry of all installed ops (built-ins included), loaded from entry points."""
    return Registry[type[Op]](OPS_GROUP)