diff --git a/toolz/functoolz.py b/toolz/functoolz.py index 6cd57ae9..49c0348e 100644 --- a/toolz/functoolz.py +++ b/toolz/functoolz.py @@ -568,3 +568,22 @@ def flip(func, a, b): [1, 2, 3] """ return func(b, a) + + +def const(value): + """Create a constant function. A constant function is a function + that returns the same value for all inputs. + + >>> c = const(1) + >>> type(c) + >>> c(2) + 1 + >>> c(3) + 1 + >>> c('a', 'b', kwarg='c') + 1 + """ + def constant_function(*args, **kwargs): + return value + + return constant_function diff --git a/toolz/tests/test_functoolz.py b/toolz/tests/test_functoolz.py index 37017e44..8831baf5 100644 --- a/toolz/tests/test_functoolz.py +++ b/toolz/tests/test_functoolz.py @@ -2,7 +2,7 @@ from toolz.functoolz import (thread_first, thread_last, memoize, curry, - compose, pipe, complement, do, juxt, flip) + compose, pipe, complement, do, juxt, flip, const) from toolz.functoolz import _num_required_args from operator import add, mul, itemgetter from toolz.utils import raises @@ -508,3 +508,15 @@ def f(a, b): return a, b assert flip(f, 'a', 'b') == ('b', 'a') + + +def test_const(): + c = const(1) + + for n in range(10): + assert c(n) == 1 + + for arg in 'abcdefghij': + assert c(n) == 1 + + assert c(1, 2, *(3, 4), kwarg=5, **{'kw': 6})