[Tutor] lambda

bob gailer bgailer at gmail.com
Sat Mar 19 16:17:15 CET 2011

In my Python Pipelines program I have the following

   opts = {
     'characters' : (lambda rec, tot: tot + len(rec), 0),
     'words' :      (lambda rec, tot: tot + len(rec.split()), 0),
     'lines' :      (lambda rec, tot: tot + 1, 0),
     'minline' :    (lambda rec, tot: min(len(rec), tot), 999999999),
     'maxline' :    (lambda rec, tot: max(len(rec), tot), 0)

The user specifies option(s) (the dictionary keys). Thje program then 
creates a class instance for each option, passing the corresponding 
function as a class initialization parameter:

     for option in options:
       func, initTotal = Count.opts.get(option , 0)
       if func:
         ctr = Count.CounterClass(func, spec, initTotal)

it made lots of sense to me to code these as lambdas.

The alternatve would have been 4 defs: (4 more lines of code and more 
indirection in code reading).

def char(rec, tot): return tot + len(rec)

Bob Gailer
Chapel Hill NC

More information about the Tutor mailing list