Skip to content

call_result_selector

Select one element from the results returned by a callable.

This module provides the select decorator, which wraps a callable and returns only the element at a given index from the callable's result.

select(fn, idx)

Wrap a callable to return a specific element of its result.

Parameters:

Name Type Description Default
fn

Callable to wrap. Its result must support integer indexing.

required
idx

Index of the element to return from the result.

required

Returns:

Type Description

A wrapped callable that invokes fn and returns result[idx].

Example
def stats():
  return 10, 20

get_count = call_result_selector.select(stats, 0)  # get_count() -> 10
Source code in py_misc_utils/call_result_selector.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def select(fn, idx):
  """Wrap a callable to return a specific element of its result.

  Args:
    fn: Callable to wrap. Its result must support integer indexing.
    idx: Index of the element to return from the result.

  Returns:
    A wrapped callable that invokes fn and returns result[idx].

  Example:
    def stats():
      return 10, 20

    get_count = call_result_selector.select(stats, 0)  # get_count() -> 10
  """

  @functools.wraps(fn)
  def wrapper(*args, **kwargs):
    """Run the wrapped callable and select one element of its result."""
    res = fn(*args, **kwargs)

    return res[idx]

  return wrapper