Skip to content

CallOp

Sub classes

Name Children Inherits
DropColumns
datacook.engine.ops.columns
    RenameColumns
    datacook.engine.ops.columns
      ChangeDtypes
      datacook.engine.ops.columns
        SortColumns
        datacook.engine.ops.columns
          AddPrefix
          datacook.engine.ops.columns
            AddSuffix
            datacook.engine.ops.columns
              SelectDtypes
              datacook.engine.ops.columns
                ConvertDtypes
                datacook.engine.ops.columns
                  CalculateColumns
                  datacook.engine.ops.columns
                    Merge
                    datacook.engine.ops.combine
                      FillMissing
                      datacook.engine.ops.missing
                        DropMissing
                        datacook.engine.ops.missing
                          DropMissingColumns
                          datacook.engine.ops.missing
                            IsMissing
                            datacook.engine.ops.missing
                              Unpivot
                              datacook.engine.ops.reshape
                                Pivot
                                datacook.engine.ops.reshape
                                `df.pivot_table(...)`: one value column, one column whose values become columns.
                                  FilterRows
                                  datacook.engine.ops.rows
                                    SortRows
                                    datacook.engine.ops.rows
                                      Head
                                      datacook.engine.ops.rows
                                      Sample
                                      datacook.engine.ops.rows
                                        DropDuplicates
                                        datacook.engine.ops.rows
                                          NLargest
                                          datacook.engine.ops.rows
                                          ResetIndex
                                          datacook.engine.ops.rows
                                            ReadOp
                                            datacook.engine.ops.sources
                                            A reader: a source op with file extensions (the format registry looks them up).
                                            SubsetCallOp
                                            datacook.engine.ops.stats
                                            A frame method on all columns or on the `columns` subset, with a new table as result.
                                            ValueCounts
                                            datacook.engine.ops.stats
                                              CorrelationWith
                                              datacook.engine.ops.stats
                                              `df.corrwith(other)`: columns matched by name, rows by position (no index).

                                                Base classes

                                                Name Children Inherits
                                                Op
                                                datacook.engine.ops.base
                                                Base class for operations. Subclasses set the metadata class variables.

                                                ⋔ Inheritance diagram

                                                graph TD
                                                  3484306131["base.CallOp"]
                                                  1539482213["base.Op"]
                                                  2751680898["builtins.object"]
                                                  1539482213 --> 3484306131
                                                  2751680898 --> 1539482213

                                                🛈 DocStrings

                                                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)
                                                

                                                :fa-brands-github: Show source on GitHub