Newbie (but improving) - Passing a function name with parameters as aparameter

MRAB google at mrabarnett.plus.com
Thu May 10 16:48:08 EDT 2007


On May 10, 6:33 pm, "Terry Reedy" <tjre... at udel.edu> wrote:
> "mosscliffe" <mcl.off... at googlemail.com> wrote in message
>
> news:1178785638.736644.312970 at e51g2000hsg.googlegroups.com...
>
> Asun Friere pointed out the central flaw in your program.  Since passing
> functions as arguments is an important concept, here, for any newbies who
> did not understand, is a restatement of the problem and the fix.
>
> | timeloop(lookup(myrecs,mypatts), 10)
>
> This does not pass the lookup function to timeloop.  Rather it calls lookup
> and passes the boolean result.  The attempt to 'call' that boolean  gives
>
> |I am trying to time a function's execution, but I get 'TypeError:
> | 'bool' object is not callable' when I try to run it.
>
> | I suspect it is my calling of 'timeloop' with the function name
> | 'lookup' and its associated variables
>
> Yes.  Make the following changes and all should be well.
>
> | def timeloop(dofunction,iters=10):
>
> def timeloop(func, args, iters=10)
>
> |   import datetime
> |   print "->-> Start of test", "LOOPS=", iters,
> | datetime.datetime.now().ctime()
> |   for x in xrange(iters):
> |      print x
> |      dofunction()
>
>      func(*args)
>
> |   print "<-<- End of test", "LOOPS=", iters,
> | datetime.datetime.now().ctime()
> |
> | def lookup(recs,patterns):
> |   matchcount = 0
> |   pattcount = 0
> |   for patt in patterns:
> |      if matchcount < pattcount:
> |         break
> |      pattcount += 1
> |      for rec in recs:
> |         # print "PATT:", patt, " REC:", rec, " PATTCOUNT=", pattcount
> |         if patt in rec:
> |            matchcount +=1
> |            break
> |   # print"MATCHCOUNT=",matchcount, "PATTCOUNT=", pattcount
> |   if matchcount == pattcount:
> |      return True
> |   else:
> |      return False
> |
> |
> |
> | myrecs = ['This is a title for Brian', 'this is detail one for brian',
> | 'this is detail two for brian', 'this is another detail one for
> | brian']
> |
> | test1 = ['one', 'nomatch']
> | test2 = ['one', 'two']
> | test3 = ['title', 'two', 'nomatcheither']
> |
> | mypatts = test1
> |
> | timeloop(lookup(myrecs,mypatts), 10)
>
> timeloop(lookup, (myrecs, mypaths), 10)
>
A smaller change would be:

timeloop(lambda: lookup(myrecs,mypatts), 10)




More information about the Python-list mailing list