Functions

identity(x)

Returns its argument.

constantly(x)

Returns function accepting any args, but always returning x.

caller(*args, **kwargs)

Returns function calling its argument with passed arguments.

partial(func, *args, **kwargs)

Like functools.partial() but returns real function. Which is useful when, for example, you want to create a method of it:

setattr(self, 'get_%s_display' % field.name, partial(_get_FIELD_display, field))

Can be also used in a variety of ways, same as functools version. DSLs is one of them:

field = dict
json_field = partial(field, json=True)
curry(func[, n])

Curries function. For example, given function of two arguments f(a, b) returns function:

lambda a: lambda b: f(a, b)

Handy to make a partial factory:

make_tester = curry(re_test)
is_word = make_tester(r'^\w+$')
is_int = make_tester(r'^[1-9]\d*$')

But see re_tester() if you really need this.

autocurry(func[, n])

Constructs a version of func returning it’s partial application if insufficient arguments passed:

def remainder(what, by):
    return what % by
rem = autocurry(remainder)

assert rem(10, 3) == rem(10)(3) == rem()(10, 3) == 1
assert map(rem(by=3), range(5)) == [0, 1, 2, 0, 1]

Can clean your code a bit when partial() makes it too cluttered.

compose(*fs)

Returns composition of functions:

extract_int = compose(int, r'\d+')

Supports Extended predicate/mapper semantics.

juxt(*fs)
ijuxt(*fs)

Function logic

complement(pred)
is_private = re_tester('^_')
is_public = complement(is_private)
iffy([pred, ]action[, default=identity])
all_fn(*fs)
is_even_int = all_fn(isa(int), even)
any_fn(*fs)
none_fn(*fs)
one_fn(*fs)
some_fn(*fs)

Constructs function calling fs one by one and returning first true result.

Enables creating functions by short-circuiting several behaviours:

get_amount = some_fn(
    lambda s: 4 if 'set of' in s else None,
    r'(\d+) wheels?',
    compose({'one': 1, 'two': 2, 'pair': 2}, r'(\w+) wheels?')
)

Table Of Contents

Previous topic

Collections

Next topic

Decorators

This Page