"bob gailer" <[EMAIL PROTECTED]> wrote

In my Python Pipelines program for the Count stage I have:

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

def characters(rec,tot): return tot + len(rec)
def words(rec,tot): return tot + len(rec.split())
etc...

Not many more characters than using lambda and
avoids the need for the dictionary lookup:

instead of

w = opts['words'](r,c)

just use:

w = words(r,c)

If you need the dictionary for dynamic lookup then just insert
the functions intop the dict:

opts = {
'characters' : characters,
'worsds' : words,
etc...
}

Consider how many more lines of code it would take if I had to use defs.

More or less by definition a Python lambda expression can
be replaced with a one-liner function.

Consider how readable it is to have the expressions all in one place.

In this case I'm not sure the gain is huge, its largely a matter of
personal preference.

Alan G.

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to