Skip to content

Commit

Permalink
ENH: Add const per pytoolz#282.
Browse files Browse the repository at this point in the history
  • Loading branch information
machinelearningdeveloper committed Oct 22, 2015
1 parent 53146dc commit ff91a73
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
22 changes: 21 additions & 1 deletion toolz/functoolz.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@


__all__ = ('identity', 'thread_first', 'thread_last', 'memoize', 'compose',
'pipe', 'complement', 'juxt', 'do', 'curry', 'flip')
'pipe', 'complement', 'juxt', 'do', 'curry', 'flip', 'const')


def identity(x):
Expand Down Expand Up @@ -568,3 +568,23 @@ def flip(func, a, b):
[1, 2, 3]
"""
return func(b, a)


def const(v):
"""Return a function that returns v.
>>> f = const(5)
>>> f()
5
>>> f(100)
5
>>> [f(i) for i in range(3)]
[5, 5, 5]
>>> f('')
5
>>> f(n=1000)
5
>>> f(1, 2, 3)
5
"""
return lambda *args, **kwargs: v
8 changes: 7 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,9 @@ def f(a, b):
return a, b

assert flip(f, 'a', 'b') == ('b', 'a')


def test_const():
f = const(5)
assert f(100) == 5
assert f(100, n=200) == 5

0 comments on commit ff91a73

Please sign in to comment.