Size: 888
Comment:
|
Size: 1646
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 43: | Line 43: |
== Controllable DIY debug == (Other hooks could be similarly added) {{{ #!python import sys, sets WHAT_TO_DEBUG = sets.Set(['io', 'core']) class deBug: def __init__(self, aspects=None): self.aspects = sets.Set(aspects) def __call__(self, f): if self.aspects & WHAT_TO_DEBUG: def newf(*args, **kwds): print >> sys.stderr, f.func_name, args, kwds f_result = f(*args, **kwds) print >> sys.stderr, f.func_name, "returned", f_result return f_result return newf else: return f @deBug(['io']) def prn(x): print x @deBug(['core']) def mult(x, y): return x * y prn(mult(2,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)
Controllable DIY debug
(Other hooks could be similarly added)
Toggle line numbers
1 import sys, sets
2
3 WHAT_TO_DEBUG = sets.Set(['io', 'core'])
4
5 class deBug:
6 def __init__(self, aspects=None):
7 self.aspects = sets.Set(aspects)
8
9 def __call__(self, f):
10 if self.aspects & WHAT_TO_DEBUG:
11 def newf(*args, **kwds):
12 print >> sys.stderr, f.func_name, args, kwds
13 f_result = f(*args, **kwds)
14 print >> sys.stderr, f.func_name, "returned", f_result
15 return f_result
16 return newf
17 else:
18 return f
19
20 @deBug(['io'])
21 def prn(x):
22 print x
23
24 @deBug(['core'])
25 def mult(x, y):
26 return x * y
27
28 prn(mult(2,2))