Size: 308
Comment:
|
Size: 888
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 11: | Line 11: |
== Pseudo-currying == {{{ #!python class curried(object): """ Decorator that returns a function that keeps returning functions until all arguments are supplied; then the original function is evaluated. """ def __init__(self, func, *a): self.func = func self.args = a def __call__(self, *a): args = self.args + a if len(args) < self.func.func_code.co_argcount: return curried(self.func, *args) else: return self.func(*args) @curried def add(a, b): return a+b add1 = add(1) print add1(2) }}} |
This page is meant to be a central repository of decorator code pieces, whether useful or not <wink>. It is NOT a page to discuss decorator syntax!
Feel free to add your suggestions (please use the current decorator syntax @dec)!
Memoize
Here's a memoizing class.
inline:memoize.py
Pseudo-currying
Toggle line numbers
1 class curried(object):
2 """
3 Decorator that returns a function that keeps returning functions
4 until all arguments are supplied; then the original function is
5 evaluated.
6 """
7
8 def __init__(self, func, *a):
9 self.func = func
10 self.args = a
11 def __call__(self, *a):
12 args = self.args + a
13 if len(args) < self.func.func_code.co_argcount:
14 return curried(self.func, *args)
15 else:
16 return self.func(*args)
17
18
19 @curried
20 def add(a, b):
21 return a+b
22
23 add1 = add(1)
24
25 print add1(2)