LBYL vs EAFP

Chris Angelico rosuav at gmail.com
Mon Feb 4 18:38:41 EST 2013


On Tue, Feb 5, 2013 at 10:16 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> 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 better
> to fail earlier than later.
>
> Comments, thoughts and opinions please.

It depends on what could cause the failure. If only a programming
error could cause x to not be a number, I'd go with your third option
- let it blow up anywhere, and follow the trace. That option requires
zero forethought, which translates directly into programmer
efficiency. But if x came from a user,  then I'd be checking inputs at
a much earlier point.

Those are the two obvious cases though, and I'm assuming your
situation is neither of them. Writing library code is half way in
between. With the specific examples given, I wouldn't like to use "x +
0" as a check; it seems dodgy. Firstly because it doesn't look like a
data type check (though a comment can help with that), and secondly
because something might very well support having a number added to it
while definitely not itself being a number - eg something along the
lines of a database cursor. So I would recommend LBYL for this
particular case.

ChrisA



More information about the Python-list mailing list