[Tutor] Why begin a function name with an underscore

Steven D'Aprano steve at pearwood.info
Thu Aug 30 21:49:53 CEST 2012


On 31/08/12 04:07, Peter Otten wrote:

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

[snip]

Yes, I had more or less come to the same conclusion earlier. The problem
is that although sufficiently large floats are all integer-valued, they're
not necessarily the integer value that you think:

py> 1e100 == 10**100
False



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


This makes no sense to me. Algorithms depend on valid input, both in real
life and in computing. If you accept invalid input, you're not executing
the algorithm that you want, you're executing a *different* algorithm.

The algorithm for "make a soft boiled egg" assumes you have an egg, not
a brick, and further that it is a chicken egg, not an ostrich egg or a
flea's egg.

The algorithm for "sort a list" requires a list, not a dict. If by some
fluke your code runs all the way to the end when you call it with a dict
argument, you haven't *sorted a list*. You've just wasted CPU cycles for
no good reason.

The algorithm for "is this a prime number?" depends on the argument being
a positive, integer-valued number. Accepting any garbage input and just
*hoping* that the function will eventually raise an *appropriate* exception
doesn't seem very wise to me. You can boil that ostrich egg for three
minutes too, but it won't taste very nice when you go to eat it.


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

I am supporting Python 2.5 onwards, so I can't use numbers.Integral.



-- 
Steven


More information about the Tutor mailing list