[Tutor] Why begin a function name with an underscore

Steven D'Aprano steve at pearwood.info
Wed Aug 29 18:21:47 CEST 2012


On 28/08/12 20:00, Peter Otten wrote:
[...]
> The differences to _validate_int() are subtle:
>
>>>> class S(str):
> ...     def __eq__(self, other): return True
> ...     def __ne__(self, other): return False
> ...     def __add__(self, other): return self
> ...
>>>> vi(S("42"))
> Traceback (most recent call last):
>    File "<stdin>", line 1, in<module>
>    File "<stdin>", line 3, in vi
> TypeError
>>>> _validate_int(S("42"))
>>>>


It seems to me that, in some ways at least, S("42") is a string
that quacks like an int (if you add it to zero, you get itself),
and therefore under duck-typing rules you might be justified in
calling it an int.

Of course, if you actually try to use it as an int, it fails to
walk like an int or swim like an int, so this is a case of
"garbage in, garbage out".

There is always tension between safety and freedom. A strict
type-check will increase safety by preventing many GIGO errors,
but it also reduces freedom to use your own WholeNumber type.
But freedom to use your own numeric types is also freedom to
abuse types like S above.



-- 
Steven


More information about the Tutor mailing list