redex.stack module

The stack is used by combinators to pass data between functions.

redex.stack.Stack

alias of tuple[Any, …]

redex.stack.StackMethod

The method from stack state to stack state.

alias of Callable[[Any, tuple[Any, …]], tuple[Any, …]]

redex.stack.constrained_call(func: Callable[[...], Any], stack: tuple[typing.Any, ...], signature: Optional[redex.function.Signature] = None) tuple[typing.Any, ...][source]

Applies the function with arguments taken from the stack.

Takes n_in arguments from the stack, reshapes them to match function’s input shape in_shape, calls the function, then pushes ouputs back onto the stack.

Parameters
  • func – a function to call.

  • stack – arguments available for the call.

  • signature – optional signature of the function. If not set, it will be inferred.

Returns

function outputs and rest of the stack.

Raises

ValueError – if a number of arguments on the stack less than required for function call.

>>> import operator as op
>>> from redex.stack import constrained_call
>>> constrained_call(func=op.add, stack=(1, 2, 0, 0))
(3, 0, 0)
redex.stack.stackmethod(method: Callable[[...], Any]) Callable[[Any, tuple[typing.Any, ...]], tuple[typing.Any, ...]][source]

Wraps a any method to a stackmethod.

The stackmethods expect an entire stack as a single argument and output its modified version.

Parameters

method – a method to wrap.

Returns

a stackmethod.

from redex.stack import stackmethod, Stack
class Add:
    @stackmethod
    def __call__(self, stack: Stack) -> Stack:
        a, b, *rest = stack
        return (a + b, *rest)
Add()(1, 2)  # -> 3
redex.stack.verify_stack_size(func: Callable[[...], Any], stack: tuple[typing.Any, ...], signature: Optional[redex.function.Signature] = None) int[source]

Verifies that the stack contains required number of arguments for function call.

Parameters
  • func – a function.

  • stack – arguments available for the call.

  • signature – optional signature of the function. If not set, it will be inferred.

Returns

stack size.

Raises

ValueError – if a number of arguments on the stack less than required for function call.