EAFP vs LBYL (was Re: A little disappointed so far)

Alex Martelli aleax at aleax.it
Mon May 19 12:51:18 EDT 2003


VanL wrote:
   ...
> I have a hard time catching all the appropriate exceptions that a
> function may throw, especially if useappropriately(thefile) is
> non-trivial.  Pure EAFP code sometimes ends up looking like this

But if useappropriately can fail in such a bewildering variety
of ways, then it will not be a simplification at all to check for
each and every one of them in advance -- it only adds *more*
complication and duplication of effort.

And the standard exceptions hierarchy has some cleverness in
its design -- e.g. each time you want to catch IOError OR
OSError together, just catch EnvironmentError, their common
baseclass!  It's rare (though not unheard of) to want to catch
them separately and distinctly.

> and you can *still* get bitten if you haven't anticipated all the ways
> in which things can go wrong.   

Absolutely -- but that goes in spades for 'checking beforehand', quite
obviously.  EAFP as an error-checking strategy isn't a silver bullet:
it just beats the pants out of LBYL.

> (And I know about bare excepts... but
> having bare excepts in your code opens up its own kettle of worms.) If I

Bare except is definitely NOT what I'm advocating, of course.  I don't
think I've ever caught anything broader than StandardError in production
code, actually (except in weird cases to accomodate 'host code' that
might be raising strings, was specifically untrusted, and the like) --
and when I do catch so widely is typically one of the few cases where
I'll use isinstance, in order to reraise at once if I've happened to
catch a KeyboardInterrupt (why the [expletive deleted] KeyboardInterrupt
couldn't have been taken away from the part of the subtree derived from
StandardError, I definitely dunno).

> really need something to work, I usually do both a pre-check (LBYL) as
> well as a just-in-case try-except, so that the number of places and ways
> in which the useappropriately() function can go wrong is minimized.
> 
> Am I seriously misguided here?

I think you are, if you truly believe that this _minimizes_ the number
of places and ways in which 'useappropriately' can go wrong -- you're
opening yourself up to race conditions and complicating your code, with
duplication of effort both in coding and at runtime, for no good reason.

That isn't to say that SOME level of LBYL isn't occasionally useful to
anticipate some failures to "ASAP" and thereby perhaps speed up
diagnosis and needed 'repair', for example -- but that definitely doesn't
'minimize' the number of failure possibilities, and all failures must
STILL be accounted for in the try/except way...


Alex





More information about the Python-list mailing list