Skip to content

ocl.cli._config

ConfigDefinedLambda

Lambda function defined in the config.

This allows lambda functions defined in the config to be pickled.

Source code in ocl/cli/_config.py
class ConfigDefinedLambda:
    """Lambda function defined in the config.

    This allows lambda functions defined in the config to be pickled.
    """

    def __init__(self, function_string: str):
        self.__setstate__(function_string)

    def __getstate__(self) -> str:
        return self.function_string

    def __setstate__(self, function_string: str):
        self.function_string = function_string
        self._fn = lambda_string_to_function(function_string)

    def __call__(self, *args, **kwargs):
        return self._fn(*args, **kwargs)

lambda_string_to_function

Convert string of the form "lambda x: x" into a callable Python function.

Source code in ocl/cli/_config.py
def lambda_string_to_function(function_string: str) -> Callable[..., Any]:
    """Convert string of the form "lambda x: x" into a callable Python function."""
    # This is a bit hacky but ensures that the syntax of the input is correct and contains
    # a valid lambda function definition without requiring to run `eval`.
    parsed = ast.parse(function_string)
    is_lambda = isinstance(parsed.body[0], ast.Expr) and isinstance(parsed.body[0].value, ast.Lambda)
    if not is_lambda:
        raise ValueError(f"'{function_string}' is not a valid lambda definition.")

    return eval(function_string)

slice_string

Split a string according to a split_char and slice.

If the output contains more than one element, join these using the split char again.

Source code in ocl/cli/_config.py
def slice_string(string: str, split_char: str, slice_str: str) -> str:
    """Split a string according to a split_char and slice.

    If the output contains more than one element, join these using the split char again.
    """
    sl = make_slice(slice_str)
    res = string.split(split_char)[sl]
    if isinstance(res, list):
        res = split_char.join(res)
    return res