[Tutor] Why begin a function name with an underscore
Peter Otten
__peter__ at web.de
Thu Aug 30 10:44:50 CEST 2012
Steven D'Aprano wrote:
> 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".
The class was written to demonstrate that your and my implementation of an
integer check may give different results, if only in corner cases with
little practical relevance.
> There is always tension between safety and freedom.
D'accord. I tend to err on the side of freedom.
>>> sum(["a", "b", "c"], "")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]
gives me the creeps even though it'd never occur to me to actually use sum()
to join a sequence of strings.
> 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.
More information about the Tutor
mailing list