LBYL vs EAFP

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Feb 4 22:52:03 EST 2013


On Tue, 05 Feb 2013 10:38:41 +1100, Chris Angelico wrote:

> 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.
[...]

> 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

Strange. To me, it looks like "oh, you're testing whether x supports 
numeric addition". I suppose the hidden assumption I'm making is that if 
x supports addition, it is a kind of number. Perhaps that's an unsafe 
assumption.


> (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.

But surely duck-typing tells us that if database cursors support the same 
sort of operations that numbers support, we should therefore treat them 
as a kind of number?

My library will not try to prevent the caller taking the average of (say) 
a dozen eggs and 10 miles. I'm not sure that it should try to prevent the 
caller from trying to take the average between two database cursors.



-- 
Steven



More information about the Python-list mailing list