exceptions == errors?

Jim Meyer jmeyer at pdi.com
Tue Apr 8 14:16:26 EDT 2003


Hello!

On Tue, 2003-04-08 at 09:34, Skip Montanaro wrote:
> Here's some timeit output against Python CVS (just cvs up'd today since
> Jeremy's and Tim's recent foray into the garbage collector).  The first set
> of trials tries both ways to test for the nonexistent attribute
> str.__nonzero__:
> 
>     >>> t = timeit.Timer(stmt="try:\n  str.__nonzero__\nexcept AttributeError:\n  pass")
>     >>> t.timeit()
>     17.419214010238647
>     >>> u = timeit.Timer(stmt="if hasattr(str, '__nonzero__'):\n  pass")
>     >>> u.timeit()
>     4.5997350215911865
> 
> The next shows access to int.__nonzero__, which does exist:
> 
>     >>> t = timeit.Timer(stmt="try:\n  int.__nonzero__\nexcept AttributeError:\n  pass")
>     >>> t.timeit()
>     1.469681978225708
>     >>> u = timeit.Timer(stmt="if hasattr(int, '__nonzero__'):\n  pass")
>     >>> u.timeit()
>     2.2288650274276733

Very cool. It's faster to try than to test for an attribute when the
attribute exists; if it doesn't, it's not. Thanks for the data as well
as the pointer to timeit, which I hadn't seen before. So, revisiting
your earlier example:

On Mon, 2003-04-07 at 17:20, Skip Montanaro wrote:
>     class Finished(exception): pass
> 
>     try:
>         for foo in some_list:
>             for bar in some_other_list:
>                 ...
>                 if conditions_met:
>                     raise Finished
>                 ...
>     except Finished:
>         pass

...and granting that the alternatives are:

  for foo in some_list:
    for bar in some_other_list:
      ...
      if conditions_met:
        break
    if conditions_met:
      break

...which is ugly or:

  fooCtr = 0
  barCtr = 0
  while not conditions_met :
    if not barCtr < len(some_other_list) :
      fooCtr += 1
      barCtr = 0
    if not fooCtr < len(some_list) :
      break
    ...

...which seems less ugly but more clunky, I think I'll tend to prefer
the exception-based code from now on and reserve the alternatives as
performance optimizations.

Thanks for the education!

--j
-- 
Jim Meyer, Geek at Large                                  jmeyer at pdi.com






More information about the Python-list mailing list