On Mon, 09 Jun 2014 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:

    return True if the condition holds, else return False
    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

Reply via email to