[Tutor] Why begin a function name with an underscore

Steven D'Aprano steve at pearwood.info
Wed Aug 29 16:13:41 CEST 2012


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,

Not really. It's trivially easy: just call

_validate_int(x)

You don't have to inspect a return result and decide what to do. If it
returns, x is an integer. If it doesn't, you get a nice exception:

TypeError for non-numeric objects

ValueError for non-integer numbers, or float/Decimal NANs and infinities


> and checking
> types in general is usually a sign of larger flaws in laying out useful
> code.


That's probably true, but especially for library code, that's not always
the case. I'm merely following the usual best-practice of Python code (to
the best of my ability), as seen in the standard library:

py> import math
py> math.factorial(2.5)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
ValueError: factorial() only accepts integral values
py> math.factorial("2")
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: an integer is required


What would you expect factorial to do in these cases, if not raise an
exception?


Speaking of argument validation, this amuses me:

http://thedailywtf.com/Articles/Argument_About_Argument_Validation.aspx



-- 
Steven


More information about the Tutor mailing list