[Tutor] Why begin a function name with an underscore
Peter Otten
__peter__ at web.de
Tue Aug 28 11:02:11 CEST 2012
Timo wrote:
> Op 28-08-12 10:06, Richard D. Moores schreef:
>> On Tue, Aug 28, 2012 at 12:13 AM, Jerry Zhang <jerry.scofield at gmail.com>
>> wrote:
>>>
>>> 2012/8/28 Richard D. Moores <rdmoores at gmail.com>
>>>
>>>> On Mon, Aug 27, 2012 at 6:33 PM, Japhy Bartlett <japhy at pearachute.com>
>>>> wrote:
>>>>
>>>>> something like:
>>>>>
>>>>> def _validate_int(obj):
>>>>> """Raise an exception if obj is not an integer."""
>>>>> m = int(obj + 0) # May raise TypeError.
>>>>> if obj != m:
>>>>> raise ValueError('expected an integer but got %r' % obj)
>>>>>
>>>>>
>>>>> is a really awkward way to test if something's an integer, and
>>>>> checking types in general is usually a sign of larger flaws in laying
>>>>> out useful code.
>>>> What the best way to test if something's an integer?
>>>
>>>>>> a = 4
>>>>>> isinstance(a, int)
>>> True
>>>>> isinstance(3., int)
>> False
>>
>> What if I wanted 3., 1234., etc. to be considered ints, as they are by
>> _validate_int() ?
>
> >>> isinstance(3., (int, float))
> True
>
> Because 3. is a float, not int.
Note that the original check takes the value into account, too:
>>> import pyprimes
>>> pyprimes._validate_int(1.0)
>>> pyprimes._validate_int(1.5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pyprimes.py", line 286, in _validate_int
raise ValueError('expected an integer but got %r' % obj)
ValueError: expected an integer but got 1.5
>>> import fractions
>>> pyprimes._validate_int(fractions.Fraction(10,2))
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.
More information about the Tutor
mailing list