None in string => TypeError?
Ian Kelly
ian.g.kelly at gmail.com
Mon Jun 9 11:50:06 EDT 2014
On Mon, Jun 9, 2014 at 9:34 AM, Roy Smith <roy at panix.com> wrote:
> We noticed recently that:
>
>>>> None in 'foo'
>
> raises (at least in Python 2.7)
>
> TypeError: 'in <string>' requires string as left operand, not NoneType
>
> This is surprising. The description of the 'in' operatator is, 'True if an item of s is equal to x, else False '. From that, I would assume it behaves as if it were written:
>
> for item in iterable:
> if item == x:
> return True
> else:
> return False
>
> why the extra type check for str.__contains__()? That seems very unpythonic. Duck typing, and all that.
I guess for the same reason that you get a TypeError if you test
whether the number 4 is in a string: it can't ever be, so it's a
nonsensical comparison. It could return False, but the comparison is
more likely to be symptomatic of a bug in the code than intentional,
so it makes some noise instead.
More information about the Python-list
mailing list