UniCoreFW

rearg()

Creates a function that invokes `func` with arguments rearranged according to the specified indexes. The argument value at the first index is provided as the first argument, the argument value at the second index is provided as the second argument, and so on. Arguments not specified in `indexes` maintain their original order after the rearranged arguments.

Implementation

Args: func: Function to rearrange arguments for. *indexes: The specified argument indexes. Returns: A new function with rearranged arguments for `func`.

Example

def example(a, b, c): return a, b, c rearranged = rearg(example, 2, 0, 1) rearranged(1, 2, 3)

Expected output: (3, 1, 2)

Source Code

def rearg(func: Callable[..., R], *indexes: int) -> Callable[..., R]: # Normalize a single list/tuple argument if len(indexes) == 1 and isinstance(indexes[0], (list, tuple)): idxs = tuple(indexes[0]) else: idxs = indexes def wrapper(*args: Any, **kwargs: Any) -> R: # Pick valid indices in the order given valid = [i for i in idxs if isinstance(i, int) and 0 <= i < len(args)] # Reordered portion reordered = [args[i] for i in valid] # Append the args not yet used remaining = [args[i] for i in range(len(args)) if i not in valid] return func(*reordered, *remaining, **kwargs) # Copy metadata for introspection wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ wrapper.__wrapped__ = func # type: ignore return wrapper