None in string => TypeError?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Jun 9 12:07:22 EDT 2014


On 2014年6月09日 08:34:42 -0700, Roy Smith wrote:
> We noticed recently that:
>>>>> None in 'foo'
>> raises (at least in Python 2.7)

That goes back to at least Python 1.5, when member tests only accepted a 
single character, not a substring:
>>> None in "abc"
Traceback (innermost last):
 File "<stdin>", line 1, in ?
TypeError: string member test needs char left operand
It's a matter of taste whether predicate functions should always return a 
bool, or sometimes raise an exception. Would you be surprised that this 
raises TypeError?
"my string".startswith(None)
A predicate function could swallow any exception, e.g. be the logical 
equivalent of:
try:
 return True if the condition holds, else return False
except:
 return False # or True as needed
but that is, I think, an anti-pattern, as it tends to hide errors rather 
than be useful. Most of the time, doing `[] in "xyz"` is an error, so 
returning False is not a useful thing to do.
I think that Python has been moving away from the "swallow exceptions" 
model in favour of letting errors propagate. E.g. hasattr used to swallow 
a lot more exceptions than it does now, and order comparisons (less than, 
greater than etc.) of dissimilar types used to return a version-dependent 
arbitrary but consistent result (e.g. all ints compared less than all 
strings), but in Python 3 that is now an error.
-- 
Steven D'Aprano
http://import-that.dreamwidth.org/


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /