functools

Starlark module for working with functools library.

The functools module is for higher-order functions: functions that act on or return other functions. In general, any callable object can be treated as a function for the purposes of this module.

Similar to functools in Python.

functools.cmp_to_key(mycmp)

Transform an old-style comparison function to a key function. Used with tools that accept key functions (such as sorted(), min(), max(), heapq.nlargest(), heapq.nsmallest(), itertools.groupby()). This function is primarily used as a transition tool for programs being converted from Python 2 which supported the use of comparison functions.

Example:

def mycmp(a, b):
    if a > b:
        return 1
    elif a < b:
        return -1
    else:
        return 0
sorted([1, 2, 4, 2], key=functools.cmp_to_key(mycmp))
[1, 2, 2, 4]

A comparison function is any callable that accept two arguments, compares them, and returns a negative number for less-than, zero for equality, or a positive number for greater-than. A key function is a callable that accepts one argument and returns another value to be used as the sort key.

Parameters:

mycmp - key function is a callable that accepts one argument and returns another value to be used as the sort key

Returns: key comparison function.

functools.reduce(function, sequence, initial=0)

Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned.

Example:

def sum(a, b):
    return a+b
functools.reduce(sum, [1,2,3,4,5,6])
21

Parameters:

  • function - function to apply.

  • sequence - collection of elements to apply function to.

  • initial - initial value.

Returns: sequence after function was applied.

Last updated