5 ms·
Somewhat related -- A few months ago I wrote a decorator that can allow for function currying [0], like so: @curry def add3(a,b,c): return a+b+c
by gamegoblin 12y ago
Somewhat related -- A few months ago I wrote a decorator that can allow for function currying [0], like so:
@curry
def add3(a,b,c): return a+b+c
# normal function application
>>> add3(1,2,3)
6
# add3(1,2) returns a unary function which is then applied to 3
>>> add3(1,2)(3)
6
# rebinding partially applied functions to another variable, then applying
>>> add2 = add3(100)
>>> add2(5,6)
111
>>> add1 = add2(3.14)
>>> add1(5)
108.14
>>> map(add1,range(5))
[103.14, 104.14, 105.14, 106.14, 107.14]
[0] https://gist.github.com/grantslatton/9221084 https://gist.github.com/grantslatton/9221084
- hcarvalhoalves 12y agoCool, but you don't need that black magic inspecting the arguments, I think you can refactor to use `functools.partial`: >>> from functools import partial >>> f = partial(lambda a, b: a + b, 1) >>> f(1) 2
- deleted 12y ago[deleted]
- gamegoblin 12y agoI suspect you will still need to inspect, otherwise you don't know when to actually evaluate. Consider applying all of the arguments at once: >>> partial(add3, 1,2,3) <functools.partial object at 0x2b335e0453c0> >>> partial(add3, 1,2,3)() 6 Note that you have to stick an extra () at the end. You could maybe try to evaluate it and catch the error telling you that there weren't enough args. Both are kinda hacky, I think.
- hcarvalhoalves 12y agoSomething like this: https://gist.github.com/hcarvalhoalves/32af119918aa0837e020 https://gist.github.com/hcarvalhoalves/32af119918aa0837e020
- gamegoblin 12y agoThat fails for something like this: def test(x, y=None): return x assert curry(test)(1) == 1 # fails
- hcarvalhoalves 12y agoI know, I left kwargs as a later exercise. You can still refactor with `partial` though since it accepts kwargs as the third argument.