Created
June 13, 2013 17:53
-
-
Save wrr/5775808 to your computer and use it in GitHub Desktop.
Experiments with Elixir inspired pipe API for python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import unittest | |
class Pipe: | |
OUT = object() | |
def __init__(self, val): | |
self._val = val | |
def __call__(self, *args): | |
if not (args): | |
return self._val | |
fun = args[0] | |
fun_args = [] | |
has_out = False | |
for arg in args[1:]: | |
if arg is Pipe.OUT: | |
has_out = True | |
fun_args.append(self._val) | |
else: | |
fun_args.append(arg) | |
if not has_out: | |
fun_args.append(self._val) | |
self._val = fun(*fun_args) | |
return self | |
def times2(x): | |
return x * 2 | |
def sub(a, b): | |
return a - b | |
class PipeTest(unittest.TestCase): | |
def test_pipe(self): | |
self.assertEqual(12, | |
Pipe(3)(times2)(times2)()) | |
def test_call_with_argument(self): | |
self.assertEqual([2, 6, 8], Pipe([1,3,4])(map, times2)()) | |
def test_explicit_position(self): | |
self.assertEqual(-9, Pipe(1)(sub, Pipe.OUT, 10)()) | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment