None in string => TypeError?

Shiyao Ma i at introo.me
Mon Jun 9 12:13:49 EDT 2014


2014-06-09 23:34 GMT+08:00 Roy Smith <roy at panix.com>:

> 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.
>

It's a little bit inconsistent.  But it's clearly documented here:
https://docs.python.org/3/reference/expressions.html#in

Which, according to its own logic, the string is not  a *container* type.
It's just some chars, and that totally makes sense for to restrict the type
of x in "str" to be convertible to type str. On the other hand, containers
like list, and tuple, they are heterogeneous by default in Python, so a
item by item comparison is needed.



-- 

吾輩は猫である。ホームーページはhttp://introo.me。
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140610/8de51459/attachment.html>


More information about the Python-list mailing list