Differences between revisions 6 and 7
Revision 6 as of 2004-08-15 08:27:54
Size: 1927
Editor: proxy1
Comment:
Revision 7 as of 2004-08-15 08:29:53
Size: 1963
Editor: proxy1
Comment:
Deletions are marked like this. Additions are marked like this.
Line 56: Line 56:
    """ Decorator which help to control what aspects to debug.
    Aspects are provided as list of arguments. It DOESN'T
    
slowdown functions which aren't supposed to be debugged.
    """ Decorator which helps to control what aspects of a program to debug
    on per-function basis
. Aspects are provided as list of arguments.
    It DOESN'T slowdown functions which aren't supposed to be debugged.

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. Exceptions are left out for simplicity of demonstration.)

Toggle line numbers
   1 import sys, sets
   2 
   3 WHAT_TO_DEBUG = sets.Set(['io', 'core'])  # change to what you need
   4 
   5 class deBug:
   6     """ Decorator which helps to control what aspects of a program to debug
   7     on per-function basis. Aspects are provided as list of arguments. 
   8     It DOESN'T slowdown functions which aren't supposed to be debugged.
   9     """
  10     def __init__(self, aspects=None):
  11         self.aspects = sets.Set(aspects)
  12 
  13     def __call__(self, f):
  14         if self.aspects & WHAT_TO_DEBUG:
  15             def newf(*args, **kwds):
  16                 print >> sys.stderr, f.func_name, args, kwds
  17                 f_result = f(*args, **kwds)
  18                 print >> sys.stderr, f.func_name, "returned", f_result
  19                 return f_result
  20             return newf
  21         else:
  22             return f
  23 
  24 @deBug(['io'])
  25 def prn(x):
  26     print x
  27 
  28 @deBug(['core'])
  29 def mult(x, y):
  30     return x * y
  31 
  32 prn(mult(2,2))

PythonDecoratorLibrary (last edited 2017-07-04 09:44:35 by mjpieters)

Unable to edit the page? See the FrontPage for instructions.