[Tutor] Why begin a function name with an underscore

Peter Otten __peter__ at web.de
Thu Aug 30 20:07:18 CEST 2012


Steven D'Aprano wrote:

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

No, I demonstrated the limitations of an alternate implementation, one that 
I prefer in spite of these limitations.
 
> 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.

Allowing floats for a primality test is a can of worms anyway. You will 
inevitably run out of significant digits:

>>> from pyprimes import isprime_naive as isprime
>>> 2**61-1
2305843009213693951
>>> isprime(2305843009213693951.0)
False
>>> isprime(2305843009213693951)
True
>>> int(2305843009213693951.0)
2305843009213693952

> 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

I think it depends on what you expect from a function. If you want it to 
execute a particular algorithm it is OK not to impose limitations on the 
input. As a building block for an actual application I'd go with a whitelist 
and require a numbers.Integral or even int (assuming Python 3) instance.



More information about the Tutor mailing list