[Tutor] Why begin a function name with an underscore

Steven D'Aprano steve at pearwood.info
Wed Aug 29 17:52:20 CEST 2012


On 28/08/12 19:02, Peter Otten wrote:
> Personally, I'm a big fan of ducktyping, so I would probably remove the
> check completely and live with the consequences:
>
>>>> >>>  pyprimes._validate_int = lambda x: None
>>>> >>>  pyprimes.isprime_naive(8.5)
> True
>
> garbage-in, garbage-out -- so what.


Duck-typing means that if an object implements the interface for an int,
or if it behaves like an int (not quite the same thing!), you can safely
treat it as an int.

8.5 is not an int, and isn't a prime number, so why is isprime claiming
it is prime? That's a bug -- or rather, it *would* be a bug except you
deliberately broke it.

There's a strong argument to be made that isprime should accept any
number and return False for those which aren't integers, rather than
raise an exception. That's reasonable behaviour.

But silently returning garbage? That's the worst thing you could do, *far*
worse than an unexpected exception or an overly-strict type-check.

Errors should occur as close as possible to where they are introduced,
and functions shouldn't return garbage -- they should either be correct,
or raise an exception. Returning some junk value is bad. Imagine if you
accidentally called len(None), and instead of raising, it returned 17.
That's how bad it is.


I'm reminded of this quote:


"I find it amusing when novice programmers believe their main job is
preventing programs from crashing. ... More experienced programmers
realize that correct code is great, code that crashes could use
improvement, but incorrect code that doesn’t crash is a horrible
nightmare." -- CD Smith




-- 
Steven


More information about the Tutor mailing list