LBYL vs EAFP
ian.g.kelly at gmail.com
Tue Feb 5 00:46:11 CET 2013
On Feb 4, 2013 4:24 PM, "Steven D'Aprano" <
steve+comp.lang.python at pearwood.info> wrote:
> The eternal conflict between "Look Before You Leap" and "Easier to Ask for
> Forgiveness than Permission" (LBYL vs EAFP) continues...
> I want to check that a value is a number. Let's say I don't care what sort
> of number -- float, int, complex, Fraction, Decimal, something else --
> that it is a number. Should I:
> Look Before I Leap:
> from numbers import Number
> if isinstance(x, Number):
> raise TypeError
> or Ask Forgiveness:
> x + 0
> where in both cases the ellipsis ... is the code I actually care about.
It seems to me that both of these are LBYL. That the second test checks by
trying an operation and potentially raising an exception is immaterial.
You're still performing a test prior to attempting the actual operation.
> A third option is not to check x at all, and hope that it will blow up at
> some arbitrary place in the middle of my code rather than silently do the
> wrong thing. I don't like this idea because, even if it fails, it is
> to fail earlier than later.
This is what I would consider EAFP. Presumably if the operation requires a
number, then it will at some point perform some kind of numerical
manipulation that will raise a TypeError if one is not passed. If the
operation succeeds, then the object supported all the operations you asked
of it, so in what sense would the program be doing the wrong thing?
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list