Skip to content

Commit

Permalink
ENH: Adds a const function to functoolz
Browse files Browse the repository at this point in the history
  • Loading branch information
llllllllll committed Oct 21, 2015
1 parent d1e3041 commit e7563cd
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
19 changes: 19 additions & 0 deletions toolz/functoolz.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
14 changes: 13 additions & 1 deletion toolz/tests/test_functoolz.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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})

0 comments on commit e7563cd

Please sign in to comment.